frontend: add api utility

This commit is contained in:
anna 2022-12-06 02:59:29 +01:00
parent 323fe471c5
commit e753ee9578
Signed by: fef
GPG key ID: EC22E476DC2D3D84

46
src/web/lib/api.ts Normal file
View file

@ -0,0 +1,46 @@
export interface Api {
delete(endpoint: string, body?: object): Promise<Response>;
get(endpoint: string, body?: object): Promise<Response>;
patch(endpoint: string, body?: object): Promise<Response>;
post(endpoint: string, body?: object): Promise<Response>;
put(endpoint: string, body?: object): Promise<Response>;
}
// we can't write these as individual functions
// because "get" is a keyword in that context
const api: Api = {
delete: (endpoint, body) => doRequest("DELETE", endpoint, body),
get: (endpoint, body) => doRequest("GET", endpoint, body),
patch: (endpoint, body) => doRequest("PATCH", endpoint, body),
post: (endpoint, body) => doRequest("POST", endpoint, body),
put: (endpoint, body) => doRequest("PUT", endpoint, body),
};
export default api;
export type Method = "DELETE" | "GET" | "PATCH" | "POST" | "PUT";
export async function doRequest(method: Method, endpoint: string, body?: object): Promise<Response> {
const params: RequestInit = { method };
const headers = [];
if (body !== undefined) {
headers.push(["Content-Type", "application/json"]);
params.body = JSON.stringify(body);
}
params.headers = headers;
const response = await fetch(endpoint, params);
if (response.ok) {
return response;
} else {
throw new ApiError(response);
}
}
export class ApiError extends Error {
public readonly response: Response;
constructor(response: Response) {
super(response.statusText);
this.response = response;
}
}