|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | +import * as http from "node:http"; |
| 3 | +import {ServerResponse} from "node:http"; |
| 4 | + |
| 5 | +/* |
| 6 | +HttpServer is a server used for testing purposes. |
| 7 | +Pass in a map of path to handler and any POST request on that path |
| 8 | +will invoke the respective handler. |
| 9 | +- listen() sets up the server to listen on a random port |
| 10 | +- close() shuts the server down |
| 11 | +- async dispose() to support async using similar to auto close in java |
| 12 | +- url to return the url the server is listening on |
| 13 | +A common usage is: |
| 14 | + await using server = new HttpServer({ |
| 15 | + "/hello": async (req, res) => { |
| 16 | + w.writeHead(200, { "content-type"": "text/plain"" }); |
| 17 | + w.end("howdy"); |
| 18 | + }, |
| 19 | + }); |
| 20 | + await server.listen(); |
| 21 | + console.log(server.url) |
| 22 | + */ |
| 23 | +export class HttpServer { |
| 24 | + private readonly server: http.Server; |
| 25 | + private _url = ""; |
| 26 | + |
| 27 | + constructor(private readonly routes: Record<string, HttpHandler>) { |
| 28 | + this.server = http.createServer((req, res) => void this.handle(req, res)); |
| 29 | + } |
| 30 | + |
| 31 | + listen(): Promise<void> { |
| 32 | + return new Promise((resolve, reject) => { |
| 33 | + this.server.once("error", reject); |
| 34 | + this.server.listen(0, "127.0.0.1", () => { |
| 35 | + this.server.off("error", reject); |
| 36 | + const addr = this.server.address() as { port: number }; |
| 37 | + this._url = `http://127.0.0.1:${addr.port}`; |
| 38 | + resolve(); |
| 39 | + }); |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + close(): Promise<void> { |
| 44 | + return new Promise((resolve, reject) => { |
| 45 | + this.server.close((err) => (err ? reject(err) : resolve())); |
| 46 | + }); |
| 47 | + } |
| 48 | + |
| 49 | + [Symbol.asyncDispose](): Promise<void> { |
| 50 | + return this.close(); |
| 51 | + } |
| 52 | + |
| 53 | + [Symbol.dispose](): Promise<void> { |
| 54 | + return this.close(); |
| 55 | + } |
| 56 | + |
| 57 | + get url(): string { |
| 58 | + if (!this._url) throw new Error("HttpServer: call listen() before accessing url"); |
| 59 | + return this._url; |
| 60 | + } |
| 61 | + |
| 62 | + private async handle( |
| 63 | + req: http.IncomingMessage, |
| 64 | + res: http.ServerResponse, |
| 65 | + ): Promise<void> { |
| 66 | + const path = req.url ?? ""; |
| 67 | + const handler = this.routes[path]; |
| 68 | + |
| 69 | + if (!handler) { |
| 70 | + res.writeHead(404); |
| 71 | + res.end(); |
| 72 | + return; |
| 73 | + } |
| 74 | + if (req.method !== "POST") { |
| 75 | + res.writeHead(405); |
| 76 | + res.end(); |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + try { |
| 81 | + await handler(req, res); |
| 82 | + } catch(err) { |
| 83 | + errorHttp(err, res) |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +// Handler has three pieces: a decoder to decode http requests to a structured request, |
| 89 | +// an endpoint to take a structured request and return a structured response, |
| 90 | +// an encoder to take a structured response and encode it on the wire as an http response. |
| 91 | +export class Handler<Req, Res> { |
| 92 | + constructor( |
| 93 | + readonly decoder: Decoder<Req>, |
| 94 | + readonly endpoint: Endpoint<Req, Res>, |
| 95 | + readonly encoder: Encoder<Res>, |
| 96 | + ) {} |
| 97 | +} |
| 98 | + |
| 99 | +// Decoder decodes an http request to a structured type. |
| 100 | +export type Decoder<Req> = (msg: http.IncomingMessage) => Promise<Req> | Req; |
| 101 | + |
| 102 | +// Encoder takes a structured type and writes it as an http response with headers and status code. |
| 103 | +export type Encoder<Res> = (res: Res, w: http.ServerResponse) => Promise<void> | void; |
| 104 | + |
| 105 | +// Endpoint is the business logic. It takes a structured request and returns a structured response. |
| 106 | +// An endpoint is agnostic of the transport; it knows nothing about http requests and responses. |
| 107 | +export type Endpoint<Req, Res> = (req: Req) => Promise<Res>; |
| 108 | + |
| 109 | +// HttpHandler takes in an http request; and actions on the http response. |
| 110 | +export type HttpHandler = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void> | void; |
| 111 | + |
| 112 | +export class HttpError extends Error { |
| 113 | + constructor(readonly status: number, readonly body: unknown) { |
| 114 | + super(`HTTP ${status}`); |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +export function newHttpHandler<Req, Res>(handler: Handler<Req, Res>): HttpHandler { |
| 119 | + return async (req, res) => { |
| 120 | + try { |
| 121 | + const request = await handler.decoder(req); |
| 122 | + const response = await handler.endpoint(request); |
| 123 | + await handler.encoder(response, res); |
| 124 | + } catch (err) { |
| 125 | + errorHttp(err, res) |
| 126 | + } |
| 127 | + }; |
| 128 | +} |
| 129 | + |
| 130 | +export async function encodeJson<T>(res: T, w: http.ServerResponse): Promise<void> { |
| 131 | + w.writeHead(200, { [contentType]: applicationJson }); |
| 132 | + w.end(JSON.stringify(res)); |
| 133 | +} |
| 134 | + |
| 135 | +export async function decodeJson<T>(msg: http.IncomingMessage): Promise<T> { |
| 136 | + const chunks: Buffer[] = []; |
| 137 | + for await (const chunk of msg) chunks.push(chunk as Buffer); |
| 138 | + return JSON.parse(Buffer.concat(chunks).toString("utf8")) as T; |
| 139 | +} |
| 140 | + |
| 141 | +function errorHttp(err: any, res: ServerResponse) { |
| 142 | + const headers = { [contentType]: applicationJson } |
| 143 | + if (err instanceof HttpError) { |
| 144 | + res.writeHead(err.status, headers); |
| 145 | + res.end(JSON.stringify(err.body)); |
| 146 | + } else if (err instanceof Error) { |
| 147 | + res.writeHead(500); |
| 148 | + res.end(err.message); |
| 149 | + } else { |
| 150 | + res.writeHead(500); |
| 151 | + res.end(); |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +const contentType = 'content-type'; |
| 156 | +const applicationJson = 'application/json'; |
0 commit comments