ApiCaller.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. // @flow
  15. import axios from 'axios'
  16. import type { AxiosXHRConfig, $AxiosXHR } from 'axios'
  17. import cookie from 'js-cookie'
  18. import logger from './ApiLogger'
  19. import notificationStore from '../stores/NotificationStore'
  20. import DomUtils from '../utils/DomUtils'
  21. type Cancelable = {
  22. requestId: string,
  23. cancel: () => void,
  24. }
  25. type RequestOptions = {
  26. url: string,
  27. method?: string,
  28. cancelId?: string,
  29. headers?: { [string]: string },
  30. data?: any,
  31. responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream',
  32. quietError?: boolean,
  33. skipLog?: boolean,
  34. }
  35. let cancelables: Cancelable[] = []
  36. const CancelToken = axios.CancelToken
  37. const addCancelable = (cancelable: Cancelable) => {
  38. cancelables.unshift(cancelable)
  39. if (cancelables.length > 100) {
  40. cancelables.pop()
  41. }
  42. }
  43. class ApiCaller {
  44. constructor() {
  45. axios.defaults.headers.common['Content-Type'] = 'application/json'
  46. }
  47. get projectId(): string {
  48. return cookie.get('projectId') || 'undefined'
  49. }
  50. cancelRequests(cancelRequestId: string) {
  51. const filteredCancelables = cancelables.filter(r => r.requestId === cancelRequestId)
  52. filteredCancelables.forEach(c => {
  53. c.cancel()
  54. })
  55. cancelables = cancelables.filter(r => r.requestId !== cancelRequestId)
  56. }
  57. get(url: string): Promise<$AxiosXHR<any>> {
  58. return this.send({ url })
  59. }
  60. send(options: RequestOptions): Promise<$AxiosXHR<any>> {
  61. return new Promise((resolve, reject) => {
  62. const axiosOptions: AxiosXHRConfig<any> = {
  63. url: options.url,
  64. method: options.method || 'GET',
  65. headers: options.headers || {},
  66. data: options.data || null,
  67. responseType: options.responseType || 'json',
  68. }
  69. if (options.cancelId) {
  70. let cancel = () => { }
  71. axiosOptions.cancelToken = new CancelToken(c => {
  72. cancel = c
  73. })
  74. addCancelable({ requestId: options.cancelId, cancel })
  75. }
  76. if (!options.skipLog) {
  77. logger.log({
  78. url: axiosOptions.url,
  79. method: axiosOptions.method || 'GET',
  80. type: 'REQUEST',
  81. })
  82. }
  83. axios(axiosOptions).then((response) => {
  84. if (!options.skipLog) {
  85. console.log(`%cResponse ${axiosOptions.url}`, 'color: #0044CA', response.data)
  86. logger.log({
  87. url: axiosOptions.url,
  88. method: axiosOptions.method || 'GET',
  89. type: 'RESPONSE',
  90. requestStatus: 200,
  91. })
  92. }
  93. resolve(response)
  94. }).catch(error => {
  95. const loginUrl = `${DomUtils.urlHashPrefix}`
  96. if (error.response) {
  97. // The request was made and the server responded with a status code
  98. // that falls out of the range of 2xx
  99. if (
  100. (error.response.status !== 401 || window.location.hash !== loginUrl) &&
  101. !options.quietError &&
  102. error.response.data) {
  103. let data = error.response.data
  104. let message = (data.error && data.error.message) || data.description
  105. if (message) {
  106. notificationStore.alert(message, 'error')
  107. }
  108. }
  109. if (error.response.status === 401 && window.location.hash !== loginUrl && error.request.responseURL.indexOf('/proxy/') === -1) {
  110. window.location.href = '/'
  111. }
  112. logger.log({
  113. url: axiosOptions.url,
  114. method: axiosOptions.method || 'GET',
  115. type: 'RESPONSE',
  116. requestStatus: error.response.status,
  117. requestError: error,
  118. })
  119. reject(error.response)
  120. } else if (error.request) {
  121. // The request was made but no response was received
  122. // `error.request` is an instance of XMLHttpRequest
  123. if (window.location.hash !== loginUrl) {
  124. notificationStore.alert('Request failed, there might be a problem with the connection to the server.', 'error')
  125. }
  126. logger.log({
  127. url: axiosOptions.url,
  128. method: axiosOptions.method || 'GET',
  129. type: 'RESPONSE',
  130. description: 'No response',
  131. requestStatus: 500,
  132. requestError: error,
  133. })
  134. reject({})
  135. } else {
  136. let canceled = error.constructor.name === 'Cancel'
  137. reject({ canceled })
  138. if (canceled) {
  139. logger.log({
  140. url: axiosOptions.url,
  141. method: axiosOptions.method || 'GET',
  142. type: 'RESPONSE',
  143. requestStatus: 'canceled',
  144. })
  145. return
  146. }
  147. // Something happened in setting up the request that triggered an Error
  148. logger.log({
  149. url: axiosOptions.url,
  150. method: axiosOptions.method || 'GET',
  151. type: 'RESPONSE',
  152. description: 'Something happened in setting up the request',
  153. requestStatus: 500,
  154. })
  155. notificationStore.alert('Request failed, there might be a problem with the connection to the server.', 'error')
  156. }
  157. })
  158. })
  159. }
  160. setDefaultHeader(name: string, value: ?string) {
  161. axios.defaults.headers.common[name] = value
  162. }
  163. }
  164. export default new ApiCaller()