tsoa
This commit is contained in:
66
src/index.ts
66
src/index.ts
@@ -1,65 +1,19 @@
|
||||
import type { Database } from "bun:sqlite";
|
||||
import { getConfig } from "./config";
|
||||
import { ensureSeededDatabase } from "./database";
|
||||
import { openApiDocument } from "./openapi";
|
||||
import { badRequest, json, matchRoute, notFound, readJson } from "./routes";
|
||||
import { createApp } from "./app";
|
||||
|
||||
export function createServer(db: Database) {
|
||||
return {
|
||||
port: getConfig().port,
|
||||
fetch: async (request: Request) => {
|
||||
if (request.method === "OPTIONS") {
|
||||
return json({ ok: true });
|
||||
}
|
||||
export function startServer(port = getConfig().port, dbPath = getConfig().dbPath) {
|
||||
const db = ensureSeededDatabase(dbPath);
|
||||
const app = createApp(db);
|
||||
|
||||
const url = new URL(request.url);
|
||||
const matched = matchRoute(request.method, url.pathname);
|
||||
|
||||
if (!matched) {
|
||||
return notFound("Route not found.");
|
||||
}
|
||||
|
||||
const { route, params } = matched;
|
||||
|
||||
if (route.servesOpenApiDocument) {
|
||||
return json(openApiDocument);
|
||||
}
|
||||
|
||||
let body: unknown = undefined;
|
||||
if (route.parseBody) {
|
||||
const parsed = route.parseBody(await readJson(request));
|
||||
if ("error" in parsed) {
|
||||
return badRequest(parsed.error);
|
||||
}
|
||||
|
||||
body = parsed.value;
|
||||
}
|
||||
|
||||
if (!route.handler) {
|
||||
return notFound("Route not found.");
|
||||
}
|
||||
|
||||
return route.handler({
|
||||
db,
|
||||
request,
|
||||
url,
|
||||
params,
|
||||
body,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function main() {
|
||||
const config = getConfig();
|
||||
const db = ensureSeededDatabase(config.dbPath);
|
||||
Bun.serve(createServer(db));
|
||||
console.info("mock-task-api:listening", {
|
||||
port: config.port,
|
||||
dbPath: config.dbPath,
|
||||
return app.listen(port, () => {
|
||||
console.info("mock-task-api:listening", {
|
||||
port,
|
||||
dbPath,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
main();
|
||||
startServer();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user