diff options
Diffstat (limited to 'src/hero.mjs')
-rw-r--r-- | src/hero.mjs | 43 |
1 files changed, 33 insertions, 10 deletions
diff --git a/src/hero.mjs b/src/hero.mjs index a8532a8..38fdde4 100644 --- a/src/hero.mjs +++ b/src/hero.mjs @@ -1,8 +1,8 @@ -import assert from "node:assert"; +import assert from "node:assert/strict"; import crypto from "node:crypto"; import http from "node:http"; -import { assocIn, getIn, first, log } from "./utils.mjs"; +import { assocIn, getIn, first, log, promisify } from "./utils.mjs"; export const normalizeSegments = segments => segments.length === 1 && segments[0] === "" ? @@ -50,13 +50,6 @@ export const addRoute = (table, methods, path, handlerFn) => { ); }; -export const buildRoutes = routes => - routes.reduce( - (acc, [methods, path, handlerFn]) => - addRoute(acc, methods, path, handlerFn), - {} - ); - export const findStaticHandler = (table, method, segments) => { const handlerFn = getIn(table, ["static", method].concat(segments)); return !handlerFn ? null : { handlerFn, params: {} }; @@ -217,4 +210,34 @@ export const chainInterceptors = arr => arr[0](req, chainInterceptors(arr.slice(1))); export const wrapHandler = (fn, arr) => - chainInterceptors(arr.concat([ (req, _next) => fn(req) ])); + arr.length === 0 ? + fn : + chainInterceptors(arr.concat([ (req, _next) => fn(req) ])); + +export const buildRoutes = (routes, globalInterceptors = []) => + routes.reduce( + (acc, [methods, path, handlerFn, interceptors = []]) => + addRoute( + acc, + methods, + path, + wrapHandler( + handlerFn, + globalInterceptors.concat(interceptors), + ), + ), + {} + ); + +export const promisifyServer = serverHandle => ({ + ref: serverHandle, + listen: promisify((...args) => serverHandle.listen(...args)), + close: promisify((...args) => serverHandle.close(...args)), +}); + +export const buildServer = (routes, globalInterceptors = []) => { + const table = buildRoutes(routes, globalInterceptors); + const requestListener = makeRequestListener(table); + const server = http.createServer(requestListener); + return promisifyServer(server); +}; |