WebApiManager.coffee 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. request = require "request"
  2. logger = require "logger-sharelatex"
  3. Settings = require "settings-sharelatex"
  4. # Don't let HTTP calls hang for a long time
  5. MAX_HTTP_REQUEST_LENGTH = 15000 # 15 seconds
  6. # DEPRECATED! This method of getting user details via track-changes is deprecated
  7. # in the way we lay out our services.
  8. # Instead, web should be responsible for collecting the raw data (user_ids) and
  9. # filling it out with calls to other services. All API calls should create a
  10. # tree-like structure as much as possible, with web as the root.
  11. module.exports = WebApiManager =
  12. sendRequest: (url, callback = (error, body) ->) ->
  13. request.get {
  14. url: "#{Settings.apis.web.url}#{url}"
  15. timeout: MAX_HTTP_REQUEST_LENGTH
  16. auth:
  17. user: Settings.apis.web.user
  18. pass: Settings.apis.web.pass
  19. sendImmediately: true
  20. }, (error, res, body)->
  21. if error?
  22. return callback(error)
  23. if res.statusCode == 404
  24. logger.log url: url, "got 404 from web api"
  25. return callback null, null
  26. if res.statusCode >= 200 and res.statusCode < 300
  27. return callback null, body
  28. else
  29. error = new Error("web returned a non-success status code: #{res.statusCode}")
  30. callback error
  31. getUserInfo: (user_id, callback = (error, userInfo) ->) ->
  32. url = "/user/#{user_id}/personal_info"
  33. logger.log user_id: user_id, "getting user info from web"
  34. WebApiManager.sendRequest url, (error, body) ->
  35. if error?
  36. logger.error err: error, user_id: user_id, url: url, "error accessing web"
  37. return callback error
  38. if body == null
  39. logger.error user_id: user_id, url: url, "no user found"
  40. return callback null, null
  41. try
  42. user = JSON.parse(body)
  43. catch error
  44. return callback(error)
  45. callback null, {
  46. id: user.id
  47. email: user.email
  48. first_name: user.first_name
  49. last_name: user.last_name
  50. }
  51. getProjectDetails: (project_id, callback = (error, details) ->) ->
  52. url = "/project/#{project_id}/details"
  53. logger.log project_id: project_id, "getting project details from web"
  54. WebApiManager.sendRequest url, (error, body) ->
  55. if error?
  56. logger.error err: error, project_id: project_id, url: url, "error accessing web"
  57. return callback error
  58. try
  59. project = JSON.parse(body)
  60. catch error
  61. return callback(error)
  62. callback null, project