UNPKG

@busy-hour/blaze

Version:

<h1 align='center'>🔥 Blaze</h1> <div align='center'> An event driven framework for 🔥 Hono.js </div>

69 lines (68 loc) • 1.82 kB
// src/handler/rest.ts import { BlazeError } from "../internal/errors/index.js"; import { isEmpty, isNil, mapToObject } from "../utils/common.js"; import { RESPONSE_TYPE } from "../utils/constant/rest/index.js"; function getRouteHandler(router, method) { if (!method) return router.all; return router[method.toLowerCase()]; } function getRestResponse(options) { const { status, headers } = options.ctx; if (!status) { return [options.result, void 0, void 0]; } if (isEmpty(headers)) { return [options.result, status, void 0]; } const resHeaders = mapToObject(options.ctx.headers); return [options.result, status, resHeaders]; } function handleRestError(options) { const { err, ctx, honoCtx } = options; let status = ctx.status ?? 500; if (err instanceof BlazeError) { status = err.status; } return honoCtx.json(err, status); } function handleRestResponse(options) { const { ctx, honoCtx } = options; const args = getRestResponse(options); switch (ctx.response) { case RESPONSE_TYPE.TEXT: return honoCtx.text(...args); case RESPONSE_TYPE.HTML: return honoCtx.html(...args); case RESPONSE_TYPE.BODY: return honoCtx.body(...args); case RESPONSE_TYPE.JSON: default: return honoCtx.json(...args); } } async function handleRest(options) { const { ctx, honoCtx, promise } = options; try { const result = await promise; if (isNil(result)) { return { resp: honoCtx.body(null, 204), ok: true }; } return { resp: await handleRestResponse({ ctx, honoCtx, result }), ok: true }; } catch (err) { return { resp: handleRestError({ ctx, err, honoCtx }), ok: false }; } } export { getRestResponse, getRouteHandler, handleRest, handleRestError, handleRestResponse };