@mark01/express-utils
Version:
npm package that contains utilities for express.js
52 lines (51 loc) • 2.15 kB
JavaScript
export class Server {
expressApp;
listenPort;
infrastructureCheck;
extraStartupChecks;
constructor(options) {
this.expressApp = options.app;
this.listenPort = options.port;
this.infrastructureCheck = options.onInfrastructureCheck;
this.extraStartupChecks = options.onExtraChecks;
}
async start() {
this.setupUncaughtExceptionHandling();
if (this.infrastructureCheck) {
const status = await this.infrastructureCheck();
console.log(`Infrastructure status: ${JSON.stringify(status)}.`);
}
if (this.extraStartupChecks) {
await this.extraStartupChecks();
console.log('All additional startup checks passed!');
}
const httpServer = this.expressApp.listen(this.listenPort, () => {
console.log(`API is running on port ${this.listenPort} in ${process.env.NODE_ENV} mode!`);
});
this.setupGracefulShutdown(httpServer);
}
setupUncaughtExceptionHandling() {
process.on('uncaughtException', (error) => {
console.error('Unhandled exception 💥! Shutting down the application.');
console.error(`Error name: ${error.name}, message: ${error.message}`);
process.exit(1);
});
}
setupGracefulShutdown(httpServer) {
const shutdownHandler = (reason, exitCode) => {
console.log(`Initiating server shutdown due to ${reason}`);
httpServer.close(() => {
console.log('Closed all active connections.');
process.exit(exitCode);
});
};
process.on('unhandledRejection', (error) => {
console.error('Unhandled promise rejection 💥! Shutting down the application.');
console.error(`Error name: ${error.name}, message: ${error.message}`);
shutdownHandler('unhandledRejection', 1);
});
process.on('SIGINT', () => shutdownHandler('SIGINT', 0));
process.on('SIGQUIT', () => shutdownHandler('SIGQUIT', 0));
process.on('SIGTERM', () => shutdownHandler('SIGTERM', 0));
}
}