Skip to content

Commit

Permalink
feat: adding a function using api client and api client as singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
barbmarcio committed Jul 8, 2024
1 parent 99ac130 commit 1ca0f76
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
31 changes: 31 additions & 0 deletions src/functions/report-event-api-class.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { apis, baseURL } from "../constants/apis.constant";
import type { Config, TopsortEvent } from "../interfaces/events.interface";
import APIClient from "../lib/api-client";

/**
* Reports an event to the Topsort API.
*
* @example
* ```js
* const event = { eventType: "test", eventData: {} };
* const config = { token: "my-token" };
* const result = await reportEvent(event, config);
* console.log(result); // { ok: true, retry: false }
* ```
*
* @param event - The event to report.
* @param config - The configuration object containing URL and token.
* @returns {Promise<{ok: boolean, retry: boolean}>} The result of the report, indicating success and if a retry is needed.
*/
export async function reportEvent(
event: TopsortEvent,
config: Config,
): Promise<{ ok: boolean; retry: boolean }> {
const url = `${config.host || baseURL}/${apis.events}`;
await APIClient.post(url, event);

return {
ok: true,
retry: false,
};
}
22 changes: 16 additions & 6 deletions src/lib/api-client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { baseURL } from "../constants/apis.constant";
import AppError from "./app-error";

class ApiClient {
class APIClient {
private baseUrl: string;

constructor(baseUrl: string) {
Expand All @@ -27,18 +28,27 @@ class ApiClient {
endpoint: string,
options: RequestInit,
): Promise<unknown> {
const response = await fetch(`${this.baseUrl}${endpoint}`, options);
return await this.handleResponse(response);
try {
const response = await fetch(`${this.baseUrl}${endpoint}`, options);
return await this.handleResponse(response);
} catch (error) {
if (error instanceof AppError) {
throw error;
}

const message = error instanceof Error ? error.message : 'Unknown error';
throw new AppError(500, 'Internal server error', message);
}
}

public async get(endpoint: string): Promise<unknown> {
return await this.request(endpoint, {
return this.request(endpoint, {
method: "GET",
});
}

public async post(endpoint: string, body: unknown): Promise<unknown> {
return await this.request(endpoint, {
return this.request(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand All @@ -48,4 +58,4 @@ class ApiClient {
}
}

export { ApiClient };
export default new APIClient(`${baseURL}`)

0 comments on commit 1ca0f76

Please sign in to comment.