Skip to content

Commit

Permalink
feat: adding high order function to wrap as validator
Browse files Browse the repository at this point in the history
  • Loading branch information
barbmarcio committed Jul 12, 2024
1 parent d7688fb commit ed41ad0
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 95 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules/
dist/
dist/
5 changes: 4 additions & 1 deletion src/functions/create-auction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { apis, baseURL } from "../constants/apis.constant";
import type { AuctionResult, TopsortAuction } from "../interfaces/auctions.interface";
import type { Config } from "../interfaces/shared.interface";
import APIClient from "../lib/api-client";
import { withValidation } from "../lib/with-validation";

export async function createAuction(body: TopsortAuction, config: Config): Promise<AuctionResult> {
async function handler(config: Config, body: TopsortAuction): Promise<AuctionResult> {
let url: URL;
try {
url = new URL(`${config.host || baseURL}/${apis.auctions}`);
Expand All @@ -14,3 +15,5 @@ export async function createAuction(body: TopsortAuction, config: Config): Promi
const result = await APIClient.post(url.toString(), body, config);
return result as AuctionResult;
}

export const createAuction = withValidation(handler);
13 changes: 8 additions & 5 deletions src/functions/report-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@ import { apis, baseURL } from "../constants/apis.constant";
import type { TopsortEvent } from "../interfaces/events.interface";
import type { Config } from "../interfaces/shared.interface";
import APIClient from "../lib/api-client";
import { withValidation } from "../lib/with-validation";

/**
* Reports an event to the Topsort API.
*
* @example
* ```js
* const event = { eventType: "test", eventData: {} };
* const config = { token: "my-token" };
* const config = { apiKey: "api-key" };
* const result = await reportEvent(event, config);
* console.log(result); // { "ok": true, "retry": false }
* console.log(result); // { "ok": true }
* ```
*
* @param event - The event to report.
* @param config - The configuration object containing URL and token.
* @returns {Promise<{ok: boolean}>} The result of the report, indicating success and if a retry is needed.
* @param config - The configuration object containing the API Key and optionally, the Host.
* @returns {Promise<{ok: boolean}>} The result of the report, indicating success.
*/
export async function reportEvent(event: TopsortEvent, config: Config): Promise<{ ok: boolean }> {
async function handler(config: Config, event: TopsortEvent): Promise<{ ok: boolean }> {
let url: URL;
try {
url = new URL(`${config.host || baseURL}/${apis.events}`);
Expand All @@ -32,3 +33,5 @@ export async function reportEvent(event: TopsortEvent, config: Config): Promise<
ok: true,
};
}

export const reportEvent = withValidation(handler);
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from "./functions/report-event";
export * from "./functions/create-auction";
export { reportEvent } from "./functions/report-event";
export { createAuction } from "./functions/create-auction";
export * from "./interfaces/events.interface";
8 changes: 8 additions & 0 deletions src/lib/validate-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { Config } from "../interfaces/shared.interface";
import AppError from "./app-error";

export function validateConfig(config: Config): void {
if (!config.apiKey) {
throw new AppError(401, "API Key is required.", {});
}
}
11 changes: 11 additions & 0 deletions src/lib/with-validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Config } from "../interfaces/shared.interface";
import { validateConfig } from "./validate-config";

export function withValidation<T extends Config, U, Args extends unknown[]>(
fn: (config: T, ...args: Args) => Promise<U>,
): (config: T, ...args: Args) => Promise<U> {
return async (config: T, ...args: Args): Promise<U> => {
validateConfig(config);
return fn(config, ...args);
};
}
78 changes: 0 additions & 78 deletions src/tests/doctest.testx.ts

This file was deleted.

19 changes: 11 additions & 8 deletions src/tests/report-event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe("reportEvent", () => {
it("should handle permanent error", async () => {
returnStatus(400, server, `${baseURL}/${apis.events}`);

await expect(reportEvent({} as TopsortEvent, { apiKey: "apiKey" })).rejects.toEqual({
await expect(reportEvent({ apiKey: "apiKey" }, {} as TopsortEvent)).rejects.toEqual({
status: 400,
statusText: "",
body: {},
Expand All @@ -24,7 +24,7 @@ describe("reportEvent", () => {

it("should handle authentication error", async () => {
returnStatus(401, server, `${baseURL}/${apis.events}`);
await expect(reportEvent({} as TopsortEvent, { apiKey: "apiKey" })).rejects.toEqual({
await expect(reportEvent({ apiKey: "apiKey" }, {} as TopsortEvent)).rejects.toEqual({
status: 401,
statusText: "",
body: {},
Expand All @@ -33,7 +33,7 @@ describe("reportEvent", () => {

it("should handle retryable error", async () => {
returnStatus(429, server, `${baseURL}/${apis.events}`);
await expect(reportEvent({} as TopsortEvent, { apiKey: "apiKey" })).rejects.toEqual({
await expect(reportEvent({ apiKey: "apiKey" }, {} as TopsortEvent)).rejects.toEqual({
status: 429,
statusText: "",
body: {},
Expand All @@ -42,7 +42,7 @@ describe("reportEvent", () => {

it("should handle server error", async () => {
returnStatus(500, server, `${baseURL}/${apis.events}`);
await expect(reportEvent({} as TopsortEvent, { apiKey: "apiKey" })).rejects.toEqual({
await expect(reportEvent({ apiKey: "apiKey" }, {} as TopsortEvent)).rejects.toEqual({
status: 500,
statusText: "",
body: {},
Expand All @@ -52,10 +52,13 @@ describe("reportEvent", () => {
it("should handle custom url", async () => {
returnStatus(200, server, `https://demo.api.topsort.com/${apis.events}`);
await expect(
reportEvent({} as TopsortEvent, {
apiKey: "apiKey",
host: "https://demo.api.topsort.com",
}),
reportEvent(
{
apiKey: "apiKey",
host: "https://demo.api.topsort.com",
},
{} as TopsortEvent,
),
).resolves.toEqual({ ok: true });
});
});

0 comments on commit ed41ad0

Please sign in to comment.