Skip to content

Instantly share code, notes, and snippets.

@RTAndrew
Last active November 25, 2024 16:08
Show Gist options
  • Save RTAndrew/209aa70eb2d6643a93023e3a68248d83 to your computer and use it in GitHub Desktop.
Save RTAndrew/209aa70eb2d6643a93023e3a68248d83 to your computer and use it in GitHub Desktop.
An HTTP abstraction that can be used when interacting with a resource (e.g: Backend)
interface HttpResponse<T> extends Response {
parsedBody?: T;
}
interface IApiResponse<T> {
result: T | null;
errors: unknown | null;
statusCode: number;
message: string;
/** The raw HTTP Response */
raw: Response;
}
const API_URL = 'http://localhost:8080/api/';
export async function http<T>(request: RequestInfo): Promise<HttpResponse<T>> {
const response: HttpResponse<T> = await fetch(request);
if (!response.ok) {
throw new Error(response.statusText);
}
try {
response.parsedBody = await response.json();
return response;
} catch (error: any) {
console.log(error);
throw new Error(error);
}
}
type THttp<T> = Omit<IApiResponse<T>, 'httpResponse'>;
export async function api<T>(path: string, args: RequestInit): Promise<IApiResponse<T>> {
try {
const { parsedBody, ...rest } = await http<THttp<T>>(
new Request(API_URL + path, {
...args,
headers: {
...args.headers,
credentials: 'include',
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
);
if (!parsedBody)
return {
statusCode: 500,
result: null,
raw: rest,
message: 'A client error happened while processing the server request',
errors: null,
};
return {
...parsedBody,
result: parsedBody?.result ?? null,
raw: rest,
};
} catch (error) {
console.log(error);
throw new Error(error as any);
}
}
export async function getRequest<T>(
path: string,
args: RequestInit = {
method: 'GET',
}
): Promise<HttpResponse<T>> {
return await http<T>(new Request(API_URL + path, args));
}
interface IPostRequestArgs extends Omit<RequestInit, 'body'> {
body: Record<string, unknown>;
}
export async function postRequest<T>(
path: string,
args: IPostRequestArgs
): Promise<IApiResponse<T>> {
return await api<T>(path, {
...args,
body: JSON.stringify(args.body),
method: 'POST',
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment