next-app/app/lib/api.ts

33 lines
1.2 KiB
TypeScript

// the base URL of the api; all requests start with it
const base_url: string = "http://localhost:4000/";
/*
export const makeGetRequest = async<T> (path: string): Promise<T> => {
return await (await fetch( base_url + path )).json();
}
*/
// generic function that makes a web request
const makeRequest = async (path: string, method: string, body?: string): Promise<Response> => {
console.log( `making ${method} request: ${base_url + path}, ${body}` );
return fetch( base_url + path, { method: method, body: body ? body : null } );
}
// the following functions are wrappers around `makeRequest`,
// for every type of request that's needed.
export const makeGetRequest = async<T> (path: string): Promise<T> => {
return (await makeRequest( path, "GET" )).json();
}
export const makePostRequest = async<T> (path: string, body: T): Promise<T> => {
return (await makeRequest( path, "POST", JSON.stringify( body ) )).json();
}
export const makePutRequest = async<T> (path: string, body: T): Promise<T> => {
return (await makeRequest( path, "PUT", JSON.stringify( body ) )).json();
}
export const makeDeleteRequest = async<T> (path: string): Promise<T> => {
return (await makeRequest( path, "DELETE" )).json();
}