RequestClient.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict'
  2. require('whatwg-fetch')
  3. module.exports = class RequestClient {
  4. constructor (uppy, opts) {
  5. this.uppy = uppy
  6. this.opts = opts
  7. this.onReceiveResponse = this.onReceiveResponse.bind(this)
  8. }
  9. get hostname () {
  10. const { uppyServer } = this.uppy.getState()
  11. const host = this.opts.host
  12. return uppyServer && uppyServer[host] ? uppyServer[host] : host
  13. }
  14. get defaultHeaders () {
  15. return {
  16. 'Accept': 'application/json',
  17. 'Content-Type': 'application/json'
  18. }
  19. }
  20. onReceiveResponse (response) {
  21. const state = this.uppy.getState()
  22. const uppyServer = state.uppyServer || {}
  23. const host = this.opts.host
  24. const headers = response.headers
  25. // Store the self-identified domain name for the uppy-server we just hit.
  26. if (headers.has('i-am') && headers.get('i-am') !== uppyServer[host]) {
  27. this.uppy.setState({
  28. uppyServer: Object.assign({}, uppyServer, {
  29. [host]: headers.get('i-am')
  30. })
  31. })
  32. }
  33. return response
  34. }
  35. get (path) {
  36. return fetch(this._getUrl(path), {
  37. method: 'get',
  38. headers: this.defaultHeaders
  39. })
  40. // @todo validate response status before calling json
  41. .then(this.onReceiveResponse)
  42. .then((res) => res.json())
  43. }
  44. post (path, data) {
  45. return fetch(this._getUrl(path), {
  46. method: 'post',
  47. headers: this.defaultHeaders,
  48. body: JSON.stringify(data)
  49. })
  50. .then(this.onReceiveResponse)
  51. .then((res) => {
  52. if (res.status < 200 || res.status > 300) {
  53. throw new Error(res.statusText)
  54. }
  55. return res.json()
  56. })
  57. }
  58. _getUrl (url) {
  59. if (url.startsWith('http:') || url.startsWith('https:')) {
  60. return url
  61. }
  62. return `${this.hostname}/${url}`
  63. }
  64. delete (path, data) {
  65. return fetch(`${this.hostname}/${path}`, {
  66. method: 'delete',
  67. credentials: 'include',
  68. headers: {
  69. 'Accept': 'application/json',
  70. 'Content-Type': 'application/json'
  71. },
  72. body: data ? JSON.stringify(data) : null
  73. })
  74. .then(this.onReceiveResponse)
  75. // @todo validate response status before calling json
  76. .then((res) => res.json())
  77. }
  78. }