feat: set up basic express server configuration

This commit adds different middlewares to the express server such as cors, helmet for security, json and url-encoded body parsers, and gzip compression. Additionally, server start logic including router configuration and MongoDB service instantiation are also handled.
This commit is contained in:
Mathis H (Avnyr) 2024-05-13 16:52:50 +02:00
parent f711dd5d49
commit 2b53168dd9
Signed by: Mathis
GPG Key ID: DD9E0666A747D126

View File

@ -0,0 +1,66 @@
import * as process from "node:process";
import { MongodbService } from "@services/databases/mongodb.service";
import { EnvUtils } from "@utils/env.util";
import { LogsUtils } from "@utils/logs.util";
import compression from "compression";
import cors from "cors";
import express, { type Express } from "express";
import helmet from "helmet";
console.log("\n\n> Starting...\n\n\n\n");
const logger = new LogsUtils("App");
const envs = new EnvUtils("App");
const app: Express = express();
// enable cors
app.use(cors());
app.options("*", cors());
// enable xss sanitizer
app.use(
helmet({
xXssProtection: true,
}),
);
app.use(helmet.xXssProtection());
// parse json request body
app.use(express.json());
// parse urlencoded request body
app.use(
express.urlencoded({
extended: true,
}),
);
// gzip compression
app.use(compression());
try {
//app.use("/auth", AuthRouter);
logger.info("Routers loaded !");
} catch (err) {
logger.error(err);
throw null;
}
try {
const port = envs.get("APP_PORT") || "3000";
app.listen(Number.parseInt(port));
logger.info(
`Server is running ! (port:${port})`,
`Memory total: ${Math.round(
process.memoryUsage().rss / 1_000_000,
)} Mio\n - Memory used by V8: ${Math.round(
process.memoryUsage().heapUsed / 1_000_000,
)} Mio`,
);
} catch (error) {
logger.error(`Server failed to start: ${error}`);
process.exit(1);
}
const mongo = new MongodbService("App");