auth-app-api / server.js
AndreaNotes1's picture
Upload 36 files
6e13570 verified
Raw History Blame Contribute Delete
1.79 kB
const { env, assertProductionSafety } = require("./config/env");
const { connectDB, disconnectDB } = require("./config/db");
const logger = require("./utils/logger");
const app = require("./app");
assertProductionSafety();
let server;
async function start() {
try {
await connectDB();
server = app.listen(env.port, () => {
logger.info(`Aynwerd API listening on port ${env.port} [${env.nodeEnv}]`);
// Logged deliberately at startup: this is the #1 source of CORS
// support confusion (a typo'd env var name, stray quotes, a
// trailing slash, or the value falling back to its localhost
// default because it was never actually set). Seeing the parsed
// array here removes all guesswork versus staring at the raw
// dashboard value.
logger.info(`CORS allow-list (CLIENT_ORIGINS parsed as): ${JSON.stringify(env.clientOrigins)}`);
});
} catch (err) {
logger.error("Failed to start server", { error: err.message });
process.exit(1);
}
}
async function shutdown(signal) {
logger.info(`Received ${signal}, shutting down gracefully...`);
if (server) {
server.close(async () => {
await disconnectDB();
process.exit(0);
});
// Force-exit if something hangs
setTimeout(() => process.exit(1), 10000).unref();
} else {
process.exit(0);
}
}
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("unhandledRejection", (reason) => {
logger.error("Unhandled promise rejection", { reason: reason?.message || reason });
});
process.on("uncaughtException", (err) => {
logger.error("Uncaught exception", { error: err.message, stack: err.stack });
process.exit(1);
});
start();