payload-rest-client
Version:
A typesafe rest api client for the payload cms.
60 lines • 2.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchFactory = void 0;
const errors_1 = require("./errors");
const parseData = async (res) => {
if (res.headers.get("content-type")?.startsWith("application/json")) {
const json = await res.json();
const asText = JSON.stringify(json);
return { data: json, asText };
}
else {
const text = await res.text();
const asText = text;
return { data: text, asText };
}
};
const fetchFactory = (options) => async (params) => {
const path = Array.isArray(params.path) ? params.path.join("/") : params.path;
const qsString = params.qs ? `?${params.qs}` : "";
const fullUrl = `${options.apiUrl}/${path}${qsString}`;
const additionalFetchOptions = options.getAdditionalFetchOptions?.({
type: params.type,
slug: params.slug,
method: params.method,
url: fullUrl,
});
const fetchFn = options.customFetchFn || fetch;
const res = await fetchFn(fullUrl, {
method: params.method,
cache: options.cache,
headers: {
...options.headers,
"Content-Type": "application/json",
},
body: params.body && JSON.stringify(params.body),
...additionalFetchOptions,
});
const data = await parseData(res);
if (options.debug) {
console.log(`type: ${params.type}`);
console.log(`slug: ${params.slug}`);
console.log(`additionalFetchOptions: ${JSON.stringify(additionalFetchOptions)}`);
console.log(`request: ${params.method} ${fullUrl} => ${res.status}`);
}
if (!res.ok) {
switch (res.status) {
case 401:
throw new errors_1.UnauthorizedError(data.asText);
case 403:
throw new errors_1.ForbiddenError(data.asText);
case 404:
throw new errors_1.NotFoundError(data.asText);
default:
throw new Error(data.asText);
}
}
return data.data;
};
exports.fetchFactory = fetchFactory;
//# sourceMappingURL=fetch.js.map