UNPKG

autumn-js

Version:
97 lines (95 loc) 2.69 kB
import { secretKeyCheck } from "./chunk-UNZHJTEY.mjs"; import { createRouterWithOptions } from "./chunk-4MEEJLXG.mjs"; import "./chunk-PO4EL4BW.mjs"; import "./chunk-MHIUO3ST.mjs"; import "./chunk-USQ76FYI.mjs"; import "./chunk-LOSIWWM2.mjs"; import "./chunk-35N7BIAE.mjs"; import { Autumn } from "./chunk-QOJMX7ML.mjs"; import "./chunk-2TEL6LR5.mjs"; import { autumnApiUrl } from "./chunk-KSG3E4Q2.mjs"; // src/libraries/backend/react-router.ts import { findRoute } from "rou3"; function autumnHandler(options) { const autumn = new Autumn({ secretKey: options.secretKey || void 0, url: autumnApiUrl }); const router = createRouterWithOptions(); let { found, error: resError } = secretKeyCheck(options?.secretKey); async function handleRequest(args) { if (!found && !options.secretKey) { throw new Response(JSON.stringify(resError), { status: resError.statusCode }); } const method = args.request.method; const url = new URL(args.request.url); const searchParams = Object.fromEntries(url.searchParams); const pathname = url.pathname; const match = findRoute(router, method, pathname); if (!match) { throw new Response("Not found", { status: 404 }); } const { data, params: pathParams } = match; const { handler } = data; let body = null; if (method === "POST" || method === "PUT" || method === "PATCH") { try { body = await args.request.json(); } catch (error) { } } const result = await handler({ autumn, body, path: url.pathname, getCustomer: async () => await options.identify(args), pathParams: { ...pathParams, ...args.params }, searchParams }); return new Response(JSON.stringify(result.body), { status: result.statusCode, headers: { "Content-Type": "application/json" } }); } async function loader(args) { if (args.request.method !== "GET") { throw new Response("Method not allowed", { status: 405 }); } const response = await handleRequest(args); const data = await response.json(); if (!response.ok) { throw new Response(JSON.stringify(data), { status: response.status }); } return data; } async function action(args) { if (args.request.method === "GET") { throw new Response("Method not allowed", { status: 405 }); } const response = await handleRequest(args); const data = await response.json(); if (!response.ok) { throw new Response(JSON.stringify(data), { status: response.status }); } return data; } return { loader, action }; } export { autumnHandler };