frontend: add api utility
This commit is contained in:
parent
323fe471c5
commit
e753ee9578
1 changed files with 46 additions and 0 deletions
46
src/web/lib/api.ts
Normal file
46
src/web/lib/api.ts
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue