feat: implementing server framework
This commit is contained in:
@@ -1,25 +1,59 @@
|
||||
import createNewDbConnection from "./database.ts";
|
||||
import IngredientService from "./Ingredient.ts";
|
||||
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: 8080 });
|
||||
const server = Deno.listen({ port: config.port ?? 8080 });
|
||||
|
||||
console.log(`HTTP webserver running. Access it at: http://localhost: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 ingredientService = new IngredientService(database);
|
||||
const ingredientResource = new resources.IngredientResource(database);
|
||||
|
||||
for await (const conn of server) {
|
||||
serveHttp(conn);
|
||||
await serveHttp(conn);
|
||||
}
|
||||
|
||||
async function serveHttp(conn: Deno.Conn) {
|
||||
const httpConn = Deno.serveHttp(conn);
|
||||
|
||||
for await (const requestEvent of httpConn) {
|
||||
const body = [];
|
||||
for (const ingredient of (await ingredientService.getAllIngredients())) {
|
||||
body.push(ingredient);
|
||||
}
|
||||
requestEvent.respondWith(Response.json(body, { status: 200 }));
|
||||
await processRequest({
|
||||
dbConnection: database,
|
||||
handleRequest: (request: StoccaTreRequest) => ingredientResource.handleRequest(request),
|
||||
}, requestEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user