kronosapi
Version:
Fast web api with Bun
56 lines (45 loc) • 1.24 kB
text/typescript
import { Server, serve } from 'bun';
import { RouteArray, RouteType } from './types';
export class KronosAPI {
_version = require('package.json').version;
_routes: RouteArray = { GET: [], POST: [], PUT: [], DELETE: [] };
#server: Server | null = null;
constructor() {
console.log(`KronosAPI v${this._version}`);
}
route(type: RouteType, path: string): KronosAPI {
this._routes[type]?.push(path);
return this;
}
getRoutes(): string {
var res = '';
Object.keys(this._routes).forEach((type) => {
var routeJoined = '\t'+this._routes[type]?.join('\n\t');
res += `${type}:\n${routeJoined}\n`;
});
return res;
}
listen(
option: {
port: number;
hostname?: string;
certFile?: string;
keyFile?: string;
} = { port: 8000 }
) {
console.log(this.getRoutes());
this.#server = serve({
...option,
fetch(req: Request) {
console.log(new URL(req.url).pathname);
return new Response('Hello Worlds');
},
});
console.log(
`Listening on port ${
option.certFile && option.keyFile ? 'https' : 'http'
}://${option.hostname || 'localhost'}:${option.port}`
);
return this.#server;
}
}