autumn-js
Version:
Autumn JS Library
102 lines (100 loc) • 2.89 kB
JavaScript
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 {
toSnakeCase
} from "./chunk-35N7BIAE.mjs";
import {
Autumn
} from "./chunk-QOJMX7ML.mjs";
import "./chunk-2TEL6LR5.mjs";
import {
autumnApiUrl
} from "./chunk-KSG3E4Q2.mjs";
// src/libraries/backend/elysia.ts
import { findRoute } from "rou3";
function autumnHandler(options) {
const { found, error: resError } = secretKeyCheck(options.secretKey);
if (!found && !options.secretKey) {
throw new Error(resError?.message || "Secret key check failed");
}
const router = createRouterWithOptions();
return function plugin(app) {
app.get("/api/autumn/*", async (context) => {
return handleRequest(context);
});
app.delete("/api/autumn/*", async (context) => {
return handleRequest(context);
});
app.post("/api/autumn/*", async (context) => {
return handleRequest(context);
});
app.put("/api/autumn/*", async (context) => {
return handleRequest(context);
});
app.patch("/api/autumn/*", async (context) => {
return handleRequest(context);
});
async function handleRequest(context) {
let { found: found2, error: resError2 } = secretKeyCheck(options.secretKey);
if (!found2) {
context.set.status = resError2.statusCode;
return resError2;
}
const autumn = new Autumn({
url: options.url || autumnApiUrl,
version: options.version,
secretKey: options.secretKey
});
const request = context.request;
const url = new URL(request.url);
const path = url.pathname;
const searchParams = Object.fromEntries(url.searchParams);
const method = request.method;
const match = findRoute(router, method, path);
if (!match) {
context.set.status = 404;
return { error: "Not found" };
}
const { data, params: pathParams } = match;
const { handler } = data;
let body = null;
if (["POST", "PUT", "PATCH"].includes(method)) {
try {
body = context.body;
} catch (error) {
body = null;
}
}
try {
const result = await handler({
autumn,
body: toSnakeCase({ obj: body }),
path,
getCustomer: async () => await options.identify(context),
pathParams,
searchParams
});
context.set.status = result.statusCode;
return result.body;
} catch (error) {
context.set.status = 500;
return {
error: "Internal server error",
message: error?.message || "Unknown error"
};
}
}
return app;
};
}
export {
autumnHandler
};