app.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * decaffeinate suggestions:
  3. * DS102: Remove unnecessary code created because of implicit returns
  4. * DS207: Consider shorter variations of null checks
  5. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  6. */
  7. const Metrics = require('@overleaf/metrics')
  8. Metrics.initialize('contacts')
  9. const Settings = require('@overleaf/settings')
  10. const logger = require('@overleaf/logger')
  11. const express = require('express')
  12. const bodyParser = require('body-parser')
  13. const mongodb = require('./app/js/mongodb')
  14. const Errors = require('./app/js/Errors')
  15. const HttpController = require('./app/js/HttpController')
  16. logger.initialize('contacts')
  17. if (Metrics.event_loop != null) {
  18. Metrics.event_loop.monitor(logger)
  19. }
  20. const app = express()
  21. app.use(Metrics.http.monitor(logger))
  22. Metrics.injectMetricsRoute(app)
  23. app.get('/user/:user_id/contacts', HttpController.getContacts)
  24. app.post(
  25. '/user/:user_id/contacts',
  26. bodyParser.json({ limit: '2mb' }),
  27. HttpController.addContact
  28. )
  29. app.get('/status', (req, res) => res.send('contacts is alive'))
  30. app.use(function (error, req, res, next) {
  31. logger.error({ err: error }, 'request errored')
  32. if (error instanceof Errors.NotFoundError) {
  33. return res.sendStatus(404)
  34. } else {
  35. return res.status(500).send('Oops, something went wrong')
  36. }
  37. })
  38. const { port } = Settings.internal.contacts
  39. const { host } = Settings.internal.contacts
  40. if (!module.parent) {
  41. // Called directly
  42. mongodb
  43. .waitForDb()
  44. .then(() => {
  45. app.listen(port, host, function (err) {
  46. if (err) {
  47. logger.fatal({ err }, `Cannot bind to ${host}:${port}. Exiting.`)
  48. process.exit(1)
  49. }
  50. return logger.debug(
  51. `contacts starting up, listening on ${host}:${port}`
  52. )
  53. })
  54. })
  55. .catch(err => {
  56. logger.fatal({ err }, 'Cannot connect to mongo. Exiting.')
  57. process.exit(1)
  58. })
  59. }
  60. module.exports = app