Browse Source

improve shutdown handling

Aneurin Barker Snook 1 year ago
parent
commit
cb1a04d35c
1 changed files with 13 additions and 14 deletions
  1. 13 14
      src/main.ts

+ 13 - 14
src/main.ts

@@ -1,3 +1,4 @@
+import type { SignalConstants } from 'os'
 import { createExpress } from './http'
 import process from 'process'
 import type { Config, Context } from './types'
@@ -5,7 +6,7 @@ import type { Config, Context } from './types'
 /**
  * Server application entrypoint.
  */
-async function main(config: Config) {
+async function main(config: Config): Promise<void> {
   // Initialize context
   const ctx = <Context>{ config }
 
@@ -18,29 +19,27 @@ async function main(config: Config) {
     // Start HTTP server
     const server = app.listen(config.http.port, config.http.host)
 
-    async function stop() {
-      await Promise.allSettled([
+    // Shut down on interrupt or terminate
+    async function stop(e: keyof SignalConstants) {
+      await Promise.all([
         // Stop server
         new Promise<void>((res, rej) => {
           server.close(err => {
             if (err) {
               console.error(err)
               rej(err)
-            } else res()
+            } else {
+              console.log('Stopped HTTP server')
+              res()
+            }
           })
         }),
       ])
-    }
 
-    // Shut down on interrupt or terminate
-    process.on('SIGINT', async () => {
-      await stop()
-      rej('Interrupted')
-    })
-    process.on('SIGTERM', async () => {
-      await stop()
-      rej('Terminated')
-    })
+      rej(new Error(`Received ${e}`))
+    }
+    process.on('SIGINT', stop)
+    process.on('SIGTERM', stop)
   })
 }