import { createServer, IncomingMessage, Server, ServerResponse } from 'http'; import type { Container } from '@celljs/core'; import { Context } from '../context'; import { Dispatcher } from '../dispatcher/dispatcher-protocol'; import { HttpRequest } from '../http/http-request'; import { Response } from '../http/http-protocol'; export type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; export namespace HttpServerUtil { /** * The Node `(req, res)` handler of the application: each request runs through the {@link Dispatcher} * in its own {@link Context}. Requests of another server (a dev server, a test, a serverless proxy) * get the members of {@link HttpRequest} first. */ export function createHandler(container: Pick): RequestListener { const dispatcher = container.get>(Dispatcher); return (req, res) => { const ctx = new Context(HttpRequest.enhance(req), res as Response); Context.run(() => dispatcher.dispatch(ctx)).catch(error => { console.error(error); if (!res.headersSent) { res.statusCode = 500; } res.end(); }); }; } /** A `node:http` server whose requests are {@link HttpRequest}s from the start. */ export function createHttpServer(handler: RequestListener): Server { return createServer({ IncomingMessage: HttpRequest }, handler); } }