@samepage/internal
Version:
Utilities used across modules - not meant for use by users directly
83 lines • 2.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiGet = exports.apiPost = void 0;
const tslib_1 = require("tslib");
const types_1 = require("./types");
const registry_1 = require("./registry");
const getApiUrl_1 = tslib_1.__importDefault(require("../utils/getApiUrl"));
const zod_1 = require("zod");
const handleFetch = (transformArgs, { method, path, domain, authorization, }) => {
const rawUrl = new URL(`${domain || (0, getApiUrl_1.default)()}/${path}`);
const [url, init] = transformArgs(rawUrl, {
method,
headers: authorization
? {
Authorization: authorization,
}
: undefined,
});
return fetch(url, init).then((r) => {
if (!r.ok) {
return r
.text()
.then((e) => Promise.reject(new Error(`${init === null || init === void 0 ? void 0 : init.method} request to ${url} failed (${r.status}): ${e}`)));
}
else if (r.status === 204) {
return {};
}
return r
.json()
.then((r) => r)
.catch((cause) => r.text().then((e) => Promise.reject(new Error(`Serialization for ${init === null || init === void 0 ? void 0 : init.method} request to ${url} failed: ${e}`, {
cause,
}))));
});
};
const handleUrlFetch = (method) => (args, _data) => {
const { data = {}, ...fetchArgs } = typeof args === "string" ? { path: args, data: _data } : args;
return handleFetch((url, init) => {
Object.entries(data).forEach(([k, v]) => url.searchParams.set(k, v));
return [
url,
{
...init,
method,
},
];
}, fetchArgs);
};
const handleBodyFetch = (method) => (args, _data) => {
const { data, ...fetchArgs } = typeof args === "string" ? { path: args, data: _data } : args;
const body = JSON.stringify(data || {});
return handleFetch((url, init) => [
url,
{
...init,
body,
headers: {
...(init.headers || {}),
"Content-Type": "application/json",
},
method,
},
], fetchArgs);
};
exports.apiPost = handleBodyFetch("POST");
exports.apiGet = handleUrlFetch("GET");
const zMethodBody = types_1.zUnauthenticatedBody.or(types_1.zAuthenticatedBody.and(types_1.zAuthHeaders.partial().or(zod_1.z.object({ authorization: zod_1.z.string() }))));
const apiClient = (data) => (0, exports.apiPost)("authorization" in data
? {
path: "page",
data,
authorization: data.authorization,
}
: {
path: "page",
data: {
notebookUuid: (0, registry_1.getSetting)("uuid"),
token: (0, registry_1.getSetting)("token"),
...data,
},
});
exports.default = apiClient;
//# sourceMappingURL=apiClient.js.map