UNPKG

burger-api

Version:

<div align="center"> <a href="https://burger-api.com"> <img src="https://github.com/user-attachments/assets/0d9b376e-1d89-479a-aa7f-e7ee3c6b2342" alt="BurgerAPI"/> </a> </div>

59 lines (58 loc) 1.81 kB
// Import stuff from Bun import { serve } from 'bun'; // Import stuff from utils import { errorResponse } from '../utils/error'; export class Server { options; server = null; /** * Initializes a new instance of the Server class with the given options. * @param options - Configuration options for the server. */ constructor(options) { this.options = options; } start(routes, handler, port, cb) { // Start Bun's native server using Bun.serve const serveOptions = { routes, fetch: async (request) => { try { return await handler(request); } catch (error) { return errorResponse(error, request, this.options.debug ?? false); } }, error(error) { console.error(error); return new Response(`Internal Server Error: ${error.message}`, { status: 500, headers: { 'Content-Type': 'text/plain', }, }); }, port, }; this.server = serve(serveOptions); if (cb) { cb(); } else { console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`); } } /** * Stops the server. * If the server is currently running, this method will stop the server and * log a message to the console indicating that the server has been stopped. * If the server is not running, this method does nothing. */ stop() { if (this.server) { this.server.stop(); console.log('Server stopped.'); } } }