54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { createServer } from "http";
|
|
import type { IncomingMessage, ServerResponse } from "http";
|
|
import { Logger } from "tslog";
|
|
import { Server } from "../compose";
|
|
|
|
/** A basic request. */
|
|
export type CoreRequest = {
|
|
/** The full URL for the request. */
|
|
url: string;
|
|
/** The HTTP method for the request. */
|
|
method: string;
|
|
/** The headers associated with the request. */
|
|
headers: { [key: string]: string | string[] | undefined };
|
|
/** The request body. */
|
|
request: IncomingMessage;
|
|
/** The response. */
|
|
response: ServerResponse;
|
|
};
|
|
|
|
export function startServer(app: Server<CoreRequest, void>) {
|
|
const logger = new Logger();
|
|
const server = createServer((req, res) => {
|
|
logger.info(req.method, req.url);
|
|
if (!req.method) {
|
|
logger.error("Missing method", req.url, req.method);
|
|
res.end();
|
|
return;
|
|
}
|
|
app({
|
|
url: req.url ?? "",
|
|
method: req.method,
|
|
headers: req.headers,
|
|
request: req,
|
|
response: res,
|
|
})
|
|
.then(() => {
|
|
logger.debug("request processed successfully");
|
|
})
|
|
.catch((error) => {
|
|
res.statusCode = 500;
|
|
logger.error("server throw an unexpected error", error);
|
|
res.write("Error!\n");
|
|
res.write(JSON.stringify(error));
|
|
})
|
|
.finally(() => {
|
|
res.end();
|
|
});
|
|
});
|
|
server.on("clientError", (err, socket) => {
|
|
socket.end("HTTP/1.1 400 Bad CoreRequest\r\n\r\n");
|
|
});
|
|
server.listen(8000);
|
|
}
|