UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

67 lines (65 loc) • 2.64 kB
import { Context, Layer } from "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 Context.Service()("everything-dev/auth/site-client") { static Live = 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 export { SiteClient, authPost, getJson, parseSiteErrorDetail, rpcPost }; //# sourceMappingURL=site-client.mjs.map