ApiCaller.js 6.6 KB

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