ApiCaller.js 6.9 KB

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