diff --git a/src/net/http/BunHttpServer.ts b/src/net/http/BunHttpServer.ts new file mode 100644 index 0000000..a399119 --- /dev/null +++ b/src/net/http/BunHttpServer.ts @@ -0,0 +1,49 @@ +import {LoggerFactory} from '@techniker-me/logger'; +import type {Server as BunServer, BunRequest, WebSocketHandler} from 'bun'; + +export type BunRouteHandler = (request: BunRequest, server: BunServer) => Promise; +export type BunMethodRoutes = { + GET: BunRouteHandler; + POST: BunRouteHandler; + PUT: BunRouteHandler; + DELETE: BunRouteHandler; + PATCH: BunRouteHandler; + OPTIONS: BunRouteHandler; +}; +export type BunRoutes = Record; + +export class BunHttpServer { + private readonly _logger = LoggerFactory.getLogger('BunHttpServer'); + private readonly _webSocketHandler: WebSocketHandler | undefined; + private readonly _routes: BunRoutes; + + constructor(routes: BunRoutes, webSocketHandler: WebSocketHandler | undefined) { + this._routes = routes; + this._webSocketHandler = webSocketHandler; + this.fetch = this.fetch.bind(this); + } + + get websocket(): WebSocketHandler | undefined { + return this._webSocketHandler; + } + + get routes(): BunRoutes { + return this._routes; + } + + public addRoute(path: string, handler: BunRouteHandler): void { + if (this._routes[path]) { + throw new Error(`Route [${path}] already exists`); + } + + this._routes[path] = handler.bind(this); + } + + public async fetch(request: BunRequest, server: BunServer): Promise { + const url = new globalThis.URL(request.url); + + this._logger.info('Received [%s] request from [%s] for unknown route [%s]', request.method, server.requestIP(request)?.address ?? 'unknown', url.pathname); + + return new Response(JSON.stringify({status: 'not-found'}), {status: 404, headers: {'Content-Type': 'application/json'}}); + } +} diff --git a/src/net/http/HttpServerFactory.ts b/src/net/http/HttpServerFactory.ts new file mode 100644 index 0000000..975202f --- /dev/null +++ b/src/net/http/HttpServerFactory.ts @@ -0,0 +1,12 @@ +import {BunHttpServer, type BunRoutes} from './BunHttpServer'; +import type {WebSocketHandler} from 'bun'; + +export default class HttpServerFactory { + public static createBunHttpServer(routes: BunRoutes, webSocketHandler: WebSocketHandler | undefined): BunHttpServer { + return new BunHttpServer(routes, webSocketHandler); + } + + private constructor() { + throw new Error('This class is a static class that may not be instantiated'); + } +}