everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
71 lines (69 loc) • 2.74 kB
JavaScript
let effect = require("effect");
//#region src/services/auth/site-client.ts
/** Extract the human detail from any error body shape the server emits —
* undefined when nothing recognizable is present. */
function parseSiteErrorDetail(status, json) {
if (json === null || json === void 0 || typeof json !== "object") return void 0;
const body = json;
const innerBody = typeof body.json === "object" && body.json !== null ? body.json : body;
if (typeof innerBody.message === "string") return innerBody.message;
if (typeof body.error === "object" && body.error !== null && !Array.isArray(body.error) && typeof body.error.message === "string") return body.error.message;
if (Array.isArray(body.error)) {
const first = body.error[0];
if (first && typeof first.message === "string") return first.message;
}
}
var SiteClient = class SiteClient extends effect.Context.Service()("everything-dev/auth/site-client") {
static Live = effect.Layer.succeed(this, SiteClient.of({
authPost: (siteUrl, path, body, cookiePair, extraHeaders, signal) => authPost(siteUrl, path, body, cookiePair, extraHeaders, signal),
rpcPost: (siteUrl, path, input, cookiePair, extraHeaders) => rpcPost(siteUrl, path, input, cookiePair, extraHeaders),
getJson: (url, cookiePair) => getJson(url, cookiePair)
}));
};
async function authPost(siteUrl, path, body, cookiePair, extraHeaders, signal) {
const headers = {
"content-type": "application/json",
origin: new URL(siteUrl).origin,
...extraHeaders
};
if (cookiePair) headers.cookie = cookiePair;
const response = await fetch(`${siteUrl.replace(/\/$/, "")}/api/auth${path}`, {
method: "POST",
headers,
body: JSON.stringify(body),
signal
});
return {
status: response.status,
json: await response.json().catch(() => ({})),
setCookie: response.headers.get("set-cookie")
};
}
async function rpcPost(siteUrl, path, input, cookiePair, extraHeaders) {
const headers = {
"content-type": "application/json",
origin: new URL(siteUrl).origin,
...extraHeaders ?? {}
};
if (cookiePair) headers.cookie = cookiePair;
const response = await fetch(`${siteUrl.replace(/\/$/, "")}${path}`, {
method: "POST",
headers,
body: JSON.stringify({ json: input })
});
return {
status: response.status,
json: await response.json().catch(() => ({})),
setCookie: response.headers.get("set-cookie")
};
}
async function getJson(url, cookiePair) {
return await (await fetch(url, { headers: cookiePair ? { cookie: cookiePair } : {} })).json().catch(() => ({}));
}
//#endregion
exports.SiteClient = SiteClient;
exports.authPost = authPost;
exports.getJson = getJson;
exports.parseSiteErrorDetail = parseSiteErrorDetail;
exports.rpcPost = rpcPost;
//# sourceMappingURL=site-client.cjs.map