From 407f817c8df37cdaac3f55f7782525fff782ba1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nick=20=27MorpheusXAUT=27=20M=C3=BCller?= Date: Sat, 25 Mar 2023 17:23:15 +0100 Subject: [PATCH] Add interrupt signal handling for graceful server shutdown --- backend/src/app.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index 7f1c251..a5f0d96 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -28,8 +28,24 @@ app.use((err, req: Request, res: Response, next: NextFunction) => { nodesched.scheduleJob('regenerate data', '*/30 * * * * *', wxService.wrappedGenerateData) wxService.wrappedGenerateData(); -app.listen(PORT, () => { +const server = app.listen(PORT, () => { console.log( `application is listening on port ${PORT}`, ); }); + +const shutdown = (signal: string) => { + console.log(`${signal} signal received. Shutting down.`); + server.close((err) => { + if (err) { + console.error(`Failed to shut down server gracefully: ${err}`); + process.exit(1); + } + + console.log('Server closed'); + process.exit(0); + }); +}; + +process.on('SIGTERM', () => shutdown('SIGTERM')); +process.on('SIGINT', () => shutdown('SIGINT'));