mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-05 09:48:44 +00:00
55 lines
1.6 KiB
TypeScript
55 lines
1.6 KiB
TypeScript
import GetApiHost from "./GetApiHost";
|
|
|
|
const { formatUrl } = GetApiHost();
|
|
|
|
type UrlRoutingFunction<UrlRouteArgs> = (urlRouteArgs: UrlRouteArgs) => string;
|
|
|
|
interface RequestHeaders {
|
|
[name: string]: string;
|
|
}
|
|
|
|
interface RouteSetup<UrlRouteArgs> {
|
|
method: string;
|
|
multipart?: boolean;
|
|
routingFunction: UrlRoutingFunction<UrlRouteArgs>;
|
|
}
|
|
|
|
//const formatUrl = (endpoint = "") =>
|
|
// `${useSsl ? "https" : "http"}://${host + endpoint}`;
|
|
|
|
const METHOD_OMITS_BODY: { [key: string]: boolean } = {
|
|
DELETE: false,
|
|
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; |