Enhance BunHttpServer with port configuration and server management

* Added a private _port property to manage the server port.
* Updated constructor to accept a BunServer instance.
* Implemented listen method to start the Bun server with specified configurations.
* Introduced stop method to gracefully stop the Bun server.
This commit is contained in:
2025-11-21 03:15:34 -05:00
parent 4f0348ec1a
commit 3a3b85f138

View File

@@ -16,11 +16,16 @@ export class BunHttpServer<T> {
private readonly _logger = LoggerFactory.getLogger('BunHttpServer');
private readonly _webSocketHandler: WebSocketHandler<T> | undefined;
private readonly _routes: BunRoutes;
private _port: number = 5000;
private _bunServer: BunServer<unknown> | undefined;
constructor(routes: BunRoutes, webSocketHandler: WebSocketHandler<T> | undefined) {
constructor(routes: BunRoutes, webSocketHandler: WebSocketHandler<T> | undefined, bunServer: BunServer<unknown>) {
this._routes = routes;
this._webSocketHandler = webSocketHandler;
this.fetch = this.fetch.bind(this);
}
get port(): number {
return this._port;
}
get websocket(): WebSocketHandler<T> | undefined {
@@ -31,15 +36,26 @@ export class BunHttpServer<T> {
return this._routes;
}
public addRoute(path: string, handler: BunRouteHandler): void {
if (this._routes[path]) {
throw new Error(`Route [${path}] already exists`);
}
public listen(port: number): Promise<void> {
this._port = port;
this._routes[path] = handler.bind(this);
return new Promise((resolve) => {
this._bunServer = Bun.serve({
fetch: this.fetch.bind(this),
port: this._port,
hostname: '0.0.0.0',
websocket: this._webSocketHandler,
routes: this._routes
});
resolve();
});
}
public async fetch(request: BunRequest, server: BunServer<unknown>): Promise<Response> {
public stop(): void {
this._bunServer?.stop();
}
private async fetch(request: BunRequest, server: BunServer<unknown>): Promise<Response> {
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);