diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/db.mjs | 5 | ||||
-rw-r--r-- | src/hero.mjs | 43 | ||||
-rw-r--r-- | src/utils.mjs | 4 |
3 files changed, 38 insertions, 14 deletions
@@ -5,13 +5,10 @@ import url from "node:url"; import sqlite from "./sqlite.cjs"; +import { promisify } from "./utils.mjs"; import { runMigrations } from "./accretion.mjs"; -export const promisify = nativeFn => (...args) => - new Promise((resolve, reject) => - nativeFn(...args, (err, data) => err ? reject(err) : resolve(data))); - export const promisifyDb = dbHandle => ({ ref: dbHandle, all: promisify((...args) => dbHandle.all(...args)), 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); +}; diff --git a/src/utils.mjs b/src/utils.mjs index e0e20a7..8ce9076 100644 --- a/src/utils.mjs +++ b/src/utils.mjs @@ -74,3 +74,7 @@ export const first = (arr, fn) => { }; export const log = o => console.error(JSON.stringify(o)); + +export const promisify = fn => (...args) => + new Promise((resolve, reject) => + fn(...args, (err, data) => err ? reject(err) : resolve(data))); |