mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-13 13:22:57 +00:00
53 lines
1.6 KiB
TypeScript
53 lines
1.6 KiB
TypeScript
import GetApiHost from "./GetApiHost";
|
|
|
|
const { host = "", useSsl = true } = GetApiHost();
|
|
|
|
type UrlRoutingFunction<UrlRouteArgs> = (urlRouteArgs: UrlRouteArgs) => string;
|
|
|
|
interface RequestHeaders {
|
|
[name: string]: string,
|
|
}
|
|
|
|
interface RouteSetup<UrlRouteArgs> {
|
|
method: string;
|
|
routingFunction: UrlRoutingFunction<UrlRouteArgs>;
|
|
}
|
|
|
|
const formatUrl = (endpoint = "") => `${ useSsl ? "https" : "http" }://${ host + endpoint }`;
|
|
|
|
const METHOD_OMITS_BODY : { [key: string] : boolean } = {
|
|
"DELETE": true,
|
|
"GET": true,
|
|
"OPTIONS": true,
|
|
"PATCH": false,
|
|
"POST": false,
|
|
"PUT": false,
|
|
}
|
|
|
|
const MakeRequest = <UrlRouteArgs, Request, Response>(routeSetup: RouteSetup<UrlRouteArgs>) : (urlRouteArgs: UrlRouteArgs, request: Request) => Promise<Response> => {
|
|
return async function(urlRouteArgs: UrlRouteArgs, request: Request) : Promise<Response> {
|
|
const endpoint = routeSetup.routingFunction(urlRouteArgs);
|
|
const method = routeSetup.method;
|
|
|
|
const methodOmitsBody = METHOD_OMITS_BODY[method] || false;
|
|
|
|
return fetch(formatUrl(endpoint), {
|
|
method,
|
|
headers: {
|
|
"Accept": "application/json",
|
|
...methodOmitsBody? {} : { "Content-Type": "application/json" }
|
|
},
|
|
credentials: 'include',
|
|
...methodOmitsBody ? {} : { body: JSON.stringify(request) },
|
|
})
|
|
.then(res => res.json())
|
|
.then(res => {
|
|
if (res && "success" in res) {
|
|
return res;
|
|
} else Promise.reject();
|
|
})
|
|
.catch(e => ({ success : false }));
|
|
}
|
|
};
|
|
|
|
export default MakeRequest; |