diff options
Diffstat (limited to 'src/hero.mjs')
-rw-r--r-- | src/hero.mjs | 23 |
1 files changed, 16 insertions, 7 deletions
diff --git a/src/hero.mjs b/src/hero.mjs index 38fdde4..aa4a5a4 100644 --- a/src/hero.mjs +++ b/src/hero.mjs @@ -2,7 +2,8 @@ import assert from "node:assert/strict"; import crypto from "node:crypto"; import http from "node:http"; -import { assocIn, getIn, first, log, promisify } from "./utils.mjs"; +import * as u from "./utils.mjs"; + export const normalizeSegments = segments => segments.length === 1 && segments[0] === "" ? @@ -45,13 +46,13 @@ export const addRoute = (table, methods, path, handlerFn) => { const segments = pathToSegments(path); const kw = hasPathParams(segments) ? "dynamic" : "static"; return methods.reduce( - (acc, el) => assocIn(acc, [kw, el].concat(segments), handlerFn), + (acc, el) => u.assocIn(acc, [kw, el].concat(segments), handlerFn), table, ); }; export const findStaticHandler = (table, method, segments) => { - const handlerFn = getIn(table, ["static", method].concat(segments)); + const handlerFn = u.getIn(table, ["static", method].concat(segments)); return !handlerFn ? null : { handlerFn, params: {} }; }; @@ -87,7 +88,7 @@ export const firstParamMatch = (tree, segments, params) => { const paramOptions = Object.keys(tree) .filter(s => s.startsWith(":")) .sort(); - return first(paramOptions, param => firstParamMatch(tree[param], nextSegments, { + return u.first(paramOptions, param => firstParamMatch(tree[param], nextSegments, { ...params, [param.slice(1)]: seg })); @@ -148,7 +149,7 @@ export const interceptorsFn = ({ logger, } = { uuidFn: crypto.randomUUID, - logger: log, + logger: u.log, }) => ({ requestId: (req, next) => next({ ...req, id: uuidFn() }), logged: async (req, next) => { @@ -204,6 +205,13 @@ export const interceptorsFn = ({ export const interceptors = interceptorsFn(); +export const defaultInterceptors = [ + interceptors.serverError, + interceptors.contentType, + interceptors.requestId, + interceptors.logged, +]; + export const chainInterceptors = arr => req => arr.length === 0 ? req : @@ -231,8 +239,9 @@ export const buildRoutes = (routes, globalInterceptors = []) => export const promisifyServer = serverHandle => ({ ref: serverHandle, - listen: promisify((...args) => serverHandle.listen(...args)), - close: promisify((...args) => serverHandle.close(...args)), + listen: u.promisify((...args) => serverHandle.listen(...args)), + close: u.promisify((...args) => serverHandle.close(...args)), + events: serverHandle, }); export const buildServer = (routes, globalInterceptors = []) => { |