app.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Metrics must be initialized before importing anything else
  2. import '@overleaf/metrics/initialize.js'
  3. import metrics from '@overleaf/metrics'
  4. import Settings from '@overleaf/settings'
  5. import logger from '@overleaf/logger'
  6. import express from 'express'
  7. import methodOverride from 'method-override'
  8. import { mongoClient } from './app/js/mongodb.js'
  9. import NotificationsController from './app/js/NotificationsController.ts'
  10. import HealthCheckController from './app/js/HealthCheckController.ts'
  11. import { isZodErrorLike } from 'zod-validation-error'
  12. import { ParamsError } from '@overleaf/validation-tools'
  13. const app = express()
  14. logger.initialize('notifications')
  15. metrics.memory.monitor(logger)
  16. metrics.open_sockets.monitor()
  17. app.use(methodOverride())
  18. app.use(express.json())
  19. app.use(metrics.http.monitor(logger))
  20. metrics.injectMetricsRoute(app)
  21. app.post('/user/:user_id', NotificationsController.addNotification)
  22. app.get('/user/:user_id', NotificationsController.getUserNotifications)
  23. app.delete(
  24. '/user/:user_id/notification/:notification_id',
  25. NotificationsController.removeNotificationId
  26. )
  27. app.delete('/user/:user_id', NotificationsController.removeNotificationKey)
  28. app.delete('/key/:key', NotificationsController.removeNotificationByKeyOnly)
  29. app.get('/key/:key/count', NotificationsController.countNotificationsByKeyOnly)
  30. app.delete(
  31. '/key/:key/bulk',
  32. NotificationsController.deleteUnreadNotificationsByKeyOnlyBulk
  33. )
  34. app.get('/status', (req, res) => res.send('notifications is up'))
  35. app.get('/health_check', HealthCheckController.check)
  36. app.get('*', (req, res) => res.sendStatus(404))
  37. app.use(handleApiError)
  38. function handleApiError(err, req, res, next) {
  39. req.logger.addFields({ err })
  40. if (err instanceof ParamsError) {
  41. req.logger.setLevel('warn')
  42. res.sendStatus(404)
  43. } else if (isZodErrorLike(err)) {
  44. req.logger.setLevel('warn')
  45. res.sendStatus(400)
  46. } else {
  47. req.logger.setLevel('error')
  48. res.sendStatus(500)
  49. }
  50. }
  51. const host = Settings.internal.notifications?.host || '127.0.0.1'
  52. const port = Settings.internal.notifications?.port || 3042
  53. try {
  54. await mongoClient.connect()
  55. } catch (err) {
  56. logger.fatal({ err }, 'Cannot connect to mongo. Exiting.')
  57. process.exit(1)
  58. }
  59. if (import.meta.url === `file://${process.argv[1]}`) {
  60. app.listen(port, host, () =>
  61. logger.debug({}, `notifications starting up, listening on ${host}:${port}`)
  62. )
  63. }
  64. export default app