main.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import type { SignalConstants } from 'os'
  2. import { createExpress } from './http'
  3. import createLogger from './log'
  4. import process from 'process'
  5. import type { Config, Context } from './types'
  6. /**
  7. * Server application entrypoint.
  8. */
  9. async function main(config: Config): Promise<void> {
  10. // Create context
  11. const ctx = <Context>{ config }
  12. // Initialize logger
  13. ctx.log = createLogger(ctx)
  14. // Initialize Express app
  15. const app = createExpress(ctx)
  16. // Start processes.
  17. // This promise can only be rejected, signifying that the app has stopped
  18. return new Promise((res, rej) => {
  19. // Start HTTP server
  20. const server = app.listen(config.http.port, config.http.host)
  21. // Shut down on interrupt or terminate
  22. async function stop(e: keyof SignalConstants) {
  23. await Promise.all([
  24. // Stop server
  25. new Promise<void>((res, rej) => {
  26. server.close(err => {
  27. if (err) {
  28. ctx.log.error(err)
  29. rej(err)
  30. } else {
  31. ctx.log.info('Stopped HTTP server')
  32. res()
  33. }
  34. })
  35. }),
  36. ])
  37. ctx.log.error(`Received ${e}`)
  38. rej()
  39. }
  40. process.on('SIGINT', e => stop(e).catch(rej))
  41. process.on('SIGTERM', e => stop(e).catch(rej))
  42. })
  43. }
  44. export default main