60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
import createNewDbConnection, {StoccaTreDbConn} from "/database.ts";
|
|
import * as resources from "/resources/main.ts";
|
|
import config from "/config.json" assert { type: "json" };
|
|
import StoccaTreRequest, {HttpMethod} from "/StoccaTreRequest.ts";
|
|
import StoccaTreRequestHandler from "/StoccaTreRequestHandler.ts";
|
|
|
|
const server = Deno.listen({ port: config.port ?? 8080 });
|
|
|
|
console.log(`Stocca Tre Server is running. Access it at: http://localhost:${ config.port }/`);
|
|
|
|
type StoccaTreApiBody = {
|
|
data: JSONObject,
|
|
error?: string,
|
|
}
|
|
|
|
function newStoccaTreApiBody(): StoccaTreApiBody {
|
|
return {
|
|
data: {},
|
|
};
|
|
}
|
|
|
|
type StoccaTreServer = {
|
|
dbConnection: StoccaTreDbConn,
|
|
handleRequest(request: StoccaTreRequest): Promise<Maybe<JSONObject>>,
|
|
}
|
|
|
|
async function processRequest(server: StoccaTreServer, requestEvent: Deno.RequestEvent) {
|
|
const route = requestEvent.request.destination;
|
|
const requestMethod = requestEvent.request.method;
|
|
console.log(route, requestMethod);
|
|
const body: StoccaTreApiBody = newStoccaTreApiBody();
|
|
const maybeResult = await server.handleRequest({
|
|
route,
|
|
method: requestMethod as HttpMethod,
|
|
});
|
|
if (maybeResult.error) {
|
|
await requestEvent.respondWith(Response.json({ ...body, error: `Internal server error: ${maybeResult.error.message}` }, { status: 500 }));
|
|
} else {
|
|
body.data = maybeResult.just;
|
|
await requestEvent.respondWith(Response.json(body, { status: 200 }));
|
|
}
|
|
}
|
|
|
|
const database = await createNewDbConnection();
|
|
const ingredientResource = new resources.IngredientResource(database);
|
|
|
|
for await (const conn of server) {
|
|
await serveHttp(conn);
|
|
}
|
|
|
|
async function serveHttp(conn: Deno.Conn) {
|
|
const httpConn = Deno.serveHttp(conn);
|
|
for await (const requestEvent of httpConn) {
|
|
await processRequest({
|
|
dbConnection: database,
|
|
handleRequest: (request: StoccaTreRequest) => ingredientResource.handleRequest(request),
|
|
}, requestEvent);
|
|
}
|
|
}
|