60 lines
2.1 KiB
TypeScript
60 lines
2.1 KiB
TypeScript
import createNewDbConnection, { StoccaTreDbConn } from "./database.ts";
|
|
import * as resources from "./resources/main.ts";
|
|
import config from "./config.ts";
|
|
import StoccaTreRequest, { HttpMethod } from "./StoccaTreRequest.ts";
|
|
import StoccaTreRequestHandler from "./StoccaTreRequestHandler.ts";
|
|
import { JSONObject } from "./JSON.ts";
|
|
|
|
type StoccaTreApiBody = {
|
|
data: JSONObject;
|
|
error?: string;
|
|
};
|
|
|
|
function newStoccaTreApiBody(): StoccaTreApiBody {
|
|
return {
|
|
data: {},
|
|
};
|
|
}
|
|
|
|
type StoccaTreServer = StoccaTreRequestHandler & {
|
|
dbConnection: StoccaTreDbConn;
|
|
};
|
|
|
|
async function processRequest(server: StoccaTreServer, requestEvent: Deno.RequestEvent) {
|
|
const route = /^https?:\/\/[^\/]*(\/.*)$/.exec(requestEvent.request.url)?.[1] ?? "/";
|
|
const requestBody = (await (await requestEvent.request.blob()).text()) ?? null;
|
|
const method: HttpMethod = requestEvent.request.method as HttpMethod;
|
|
const body: StoccaTreApiBody = newStoccaTreApiBody();
|
|
const result = await server.handleRequest(new StoccaTreRequest(method, route, requestBody));
|
|
if (result.error) {
|
|
await requestEvent.respondWith(
|
|
Response.json({
|
|
...body,
|
|
error: `Internal server error: ${result.error.message}`,
|
|
}, { status: 500 }),
|
|
);
|
|
} else {
|
|
body.data = result.just;
|
|
await requestEvent.respondWith(Response.json(body, { status: 200 }));
|
|
}
|
|
}
|
|
|
|
const stoccaTreListener = Deno.listen({ port: config.port ?? 8080 });
|
|
|
|
console.log(`Stocca Tre Server is running. Access it at: http://localhost:${config.port}/`);
|
|
|
|
const database = createNewDbConnection();
|
|
const ingredientResource = new resources.IngredientResource(database);
|
|
const userResource = new resources.UserResource(database);
|
|
const stoccaTreServer: StoccaTreServer = {
|
|
dbConnection: database,
|
|
handleRequest: (request: StoccaTreRequest) => ingredientResource.handleRequest(request),
|
|
};
|
|
|
|
for await (const conn of stoccaTreListener) {
|
|
const httpConn = Deno.serveHttp(conn);
|
|
for await (const requestEvent of httpConn) {
|
|
await processRequest(stoccaTreServer, requestEvent);
|
|
}
|
|
}
|