Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 30 additions & 23 deletions src/Request.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {Multipart} from "multipart-ts";
import http, {OutgoingHttpHeader} from "node:http";
import stream from "node:stream";
import {Multipart} from "multipart-ts";

/**
* An incoming HTTP request from a connected client.
Expand Down Expand Up @@ -33,7 +33,12 @@ export class Request {
* @param headers See {@link Request#headers}.
* @param bodyStream See {@link Request#bodyStream}.
*/
protected constructor(method: Request["method"], url: Request["url"], headers: Request["headers"], bodyStream: Request["bodyStream"]) {
protected constructor(
method: Request["method"],
url: Request["url"],
headers: Request["headers"],
bodyStream: Request["bodyStream"],
) {
this.method = method;
this.url = url;
this.headers = headers;
Expand All @@ -45,8 +50,14 @@ export class Request {
* @throws {@link Request.BadUrlError} If the request URL is invalid.
*/
public static incomingMessage(incomingMessage: http.IncomingMessage) {
const auth = incomingMessage.headers.authorization?.toLowerCase().startsWith("basic ")
? Buffer.from(incomingMessage.headers.authorization.substring("basic ".length), "base64").toString()
const auth =
incomingMessage.headers.authorization
?.toLowerCase()
.startsWith("basic ")
? Buffer.from(
incomingMessage.headers.authorization
.substring("basic ".length), "base64"
).toString()
: null;

const url = `http://${auth ? `${auth}@` : ""}${process.env.HOST ?? "localhost"}${incomingMessage.url ?? "/"}`;
Expand All @@ -55,12 +66,21 @@ export class Request {

const headers = Request.headersFromNodeDict(incomingMessage.headers);

return new Request(
incomingMessage.method as Request.Method,
new URL(url),
headers,
incomingMessage
)
return new Request(incomingMessage.method as Request.Method, new URL(url), headers, incomingMessage);
}

/**
* @internal
*/
public static headersFromNodeDict(headers: Record<string, OutgoingHttpHeader | undefined>): Headers {
return new Headers(Object.entries(headers)
.filter((e) => e[1] !== undefined)
.flatMap<[string, string]>(([key, value]) =>
value instanceof Array
? value.map<[string, string]>(v => [key, v])
: [[key, String(value)]]
)
);
}

/**
Expand Down Expand Up @@ -135,19 +155,6 @@ export class Request {
public async text(): Promise<string> {
return (await this.blob()).text();
}

/**
* @internal
*/
public static headersFromNodeDict(headers: Record<string, OutgoingHttpHeader | undefined>): Headers {
return new Headers(
(Object.entries(headers)
.filter(([, v]) => v !== undefined) as [string, Exclude<typeof headers[string], undefined>][])
.flatMap<[string, string]>(([key, value]) =>value instanceof Array
? value.map<[string, string]>(v => [key, v])
: [[key, String(value)]])
);
}
}

export namespace Request {
Expand Down
33 changes: 25 additions & 8 deletions src/ServerErrorRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,41 @@ import {TextResponse} from "./response/TextResponse.js";
class ServerErrorRegistry {
private readonly responses: Record<ServerErrorRegistry.ErrorCodes, Response>;

/**
* Create a new server error registry initialised with default responses.
*/
public constructor() {
this.responses = {
[ServerErrorRegistry.ErrorCodes.BAD_URL]:
new TextResponse("Bad request URL.", 400),

[ServerErrorRegistry.ErrorCodes.NO_ROUTE]:
new TextResponse("No route in this registry matches the request.", 404),

[ServerErrorRegistry.ErrorCodes.INTERNAL]:
new TextResponse("An internal error occurred.", 500),
};
}

/**
* Replace server error response by registering a new custom response.
* @param code The server error code.
* @param response The response to send.
*/
public register(code: ServerErrorRegistry.ErrorCodes, response: Response) {
this.responses[code] = response;
}

/** @internal */
public _get(code: ServerErrorRegistry.ErrorCodes): Response {
return this.responses[code];
}

public constructor() {
this.responses = {
[ServerErrorRegistry.ErrorCodes.BAD_URL]: new TextResponse("Bad request URL.", 400),
[ServerErrorRegistry.ErrorCodes.NO_ROUTE]: new TextResponse("No route in this registry matches the request.", 404),
[ServerErrorRegistry.ErrorCodes.INTERNAL]: new TextResponse("An internal error occurred.", 500),
};
}
}

namespace ServerErrorRegistry {
/**
* Server error codes
*/
export const enum ErrorCodes {
BAD_URL,
NO_ROUTE,
Expand Down
4 changes: 2 additions & 2 deletions src/response/JsonResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export class JsonResponse<T> extends TextResponse {
return v.toISOString();
if (typeof v === "bigint")
return v <= BigInt(Number.MAX_SAFE_INTEGER)
? Number(v)
: v.toString();
? Number(v)
: v.toString();
return v;
}));
}
Expand Down
14 changes: 7 additions & 7 deletions src/response/Response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ export abstract class Response {
this.headers = new Headers(headers);
}

/**
* @internal
*/
public _send(...args: Parameters<Response["send"]>): ReturnType<Response["send"]> {
return this.send(...args);
}

/**
* Set the HTTP response status code and headers.
*/
Expand All @@ -38,11 +45,4 @@ export abstract class Response {
* Called once by the server to send the response.
*/
protected abstract send(res: http.ServerResponse, server: Server, req?: Request): void | Promise<void>;

/**
* @internal
*/
public _send(...args: Parameters<Response["send"]>): ReturnType<Response["send"]> {
return this.send(...args);
}
}