ApiCaller.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 } from 'axios'
  17. import cookie from 'js-cookie'
  18. import cacher from './Cacher'
  19. import logger from './ApiLogger'
  20. import notificationStore from '../stores/NotificationStore'
  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. cache?: ?boolean,
  35. cacheFor?: ?number,
  36. }
  37. let cancelables: Cancelable[] = []
  38. const CancelToken = axios.CancelToken
  39. const addCancelable = (cancelable: Cancelable) => {
  40. cancelables.unshift(cancelable)
  41. if (cancelables.length > 100) {
  42. cancelables.pop()
  43. }
  44. }
  45. const isOnLoginPage = (): boolean => {
  46. if (window.env.ENV === 'development') {
  47. return window.location.hash === '#/login'
  48. }
  49. return window.location.pathname === '/login'
  50. }
  51. class ApiCaller {
  52. constructor() {
  53. axios.defaults.headers.common['Content-Type'] = 'application/json'
  54. }
  55. get projectId(): string {
  56. return cookie.get('projectId') || 'undefined'
  57. }
  58. cancelRequests(cancelRequestId: string) {
  59. const filteredCancelables = cancelables.filter(r => r.requestId === cancelRequestId)
  60. filteredCancelables.forEach(c => {
  61. c.cancel()
  62. })
  63. cancelables = cancelables.filter(r => r.requestId !== cancelRequestId)
  64. }
  65. get(url: string): Promise<any> {
  66. return this.send({ url })
  67. }
  68. send(options: RequestOptions): Promise<any> {
  69. let cachedData = options.cache ? cacher.load({ key: options.url, maxAge: options.cacheFor }) : null
  70. if (cachedData) {
  71. return Promise.resolve({ data: cachedData })
  72. }
  73. return new Promise((resolve, reject) => {
  74. const axiosOptions: AxiosXHRConfig<any> = {
  75. url: options.url,
  76. method: options.method || 'GET',
  77. headers: options.headers || {},
  78. data: options.data || null,
  79. responseType: options.responseType || 'json',
  80. }
  81. if (options.cancelId) {
  82. let cancel = () => { }
  83. axiosOptions.cancelToken = new CancelToken(c => {
  84. cancel = c
  85. })
  86. addCancelable({ requestId: options.cancelId, cancel })
  87. }
  88. if (!options.skipLog) {
  89. logger.log({
  90. url: axiosOptions.url,
  91. method: axiosOptions.method || 'GET',
  92. type: 'REQUEST',
  93. })
  94. }
  95. axios(axiosOptions).then((response) => {
  96. if (!options.skipLog) {
  97. console.log(`%cResponse ${axiosOptions.url}`, 'color: #0044CA', response.data)
  98. logger.log({
  99. url: axiosOptions.url,
  100. method: axiosOptions.method || 'GET',
  101. type: 'RESPONSE',
  102. requestStatus: 200,
  103. })
  104. }
  105. if (options.cache) {
  106. cacher.save({ key: options.url, data: response.data })
  107. }
  108. resolve(response)
  109. }).catch(error => {
  110. if (error.response) {
  111. // The request was made and the server responded with a status code
  112. // that falls out of the range of 2xx
  113. if (
  114. (error.response.status !== 401 || !isOnLoginPage()) &&
  115. !options.quietError) {
  116. let data = error.response.data
  117. let message = (data && data.error && data.error.message) || (data && data.description)
  118. message = message || `${error.response.statusText || error.response.status} ${options.url}`
  119. if (message) {
  120. notificationStore.alert(message, 'error')
  121. }
  122. }
  123. if (error.response.status === 401 && !isOnLoginPage() && error.request.responseURL.indexOf('/proxy/') === -1) {
  124. window.location.href = '/login'
  125. }
  126. logger.log({
  127. url: axiosOptions.url,
  128. method: axiosOptions.method || 'GET',
  129. type: 'RESPONSE',
  130. requestStatus: error.response.status,
  131. requestError: error,
  132. })
  133. reject(error.response)
  134. } else if (error.request) {
  135. // The request was made but no response was received
  136. // `error.request` is an instance of XMLHttpRequest
  137. if (!isOnLoginPage() && !options.quietError) {
  138. notificationStore.alert(`Request failed, there might be a problem with the connection to the server. ${options.url}`, 'error')
  139. }
  140. logger.log({
  141. url: axiosOptions.url,
  142. method: axiosOptions.method || 'GET',
  143. type: 'RESPONSE',
  144. description: 'No response',
  145. requestStatus: 500,
  146. requestError: error,
  147. })
  148. reject({})
  149. } else {
  150. let canceled = error.constructor.name === 'Cancel'
  151. reject({ canceled })
  152. if (canceled) {
  153. logger.log({
  154. url: axiosOptions.url,
  155. method: axiosOptions.method || 'GET',
  156. type: 'RESPONSE',
  157. requestStatus: 'canceled',
  158. })
  159. return
  160. }
  161. // Something happened in setting up the request that triggered an Error
  162. logger.log({
  163. url: axiosOptions.url,
  164. method: axiosOptions.method || 'GET',
  165. type: 'RESPONSE',
  166. description: 'Something happened in setting up the request',
  167. requestStatus: 500,
  168. })
  169. notificationStore.alert(`Request failed, there might be a problem with the connection to the server. ${options.url}`, 'error')
  170. }
  171. })
  172. })
  173. }
  174. setDefaultHeader(name: string, value: ?string) {
  175. axios.defaults.headers.common[name] = value
  176. }
  177. }
  178. export default new ApiCaller()