ApiCaller.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. let alertMessage = message || `${error.response.statusText || error.response.status} ${truncateUrl(options.url)}`
  137. let status = error.response.status && error.response.statusText
  138. ? `${error.response.status} - ${error.response.statusText}`
  139. : error.response.statusText || error.response.status
  140. notificationStore.alert(alertMessage, 'error', {
  141. action: {
  142. label: 'View details',
  143. callback: () => ({ request: axiosOptions, error: { status, message } }),
  144. },
  145. })
  146. }
  147. if (error.request.responseURL.indexOf('/proxy/') === -1) {
  148. redirect(error.response.status)
  149. }
  150. logger.log({
  151. url: axiosOptions.url,
  152. method: axiosOptions.method || 'GET',
  153. type: 'RESPONSE',
  154. requestStatus: error.response.status,
  155. requestError: error,
  156. })
  157. reject(error.response)
  158. } else if (error.request) {
  159. // The request was made but no response was received
  160. // `error.request` is an instance of XMLHttpRequest
  161. if (!isOnLoginPage() && !options.quietError) {
  162. notificationStore.alert(
  163. `Request failed, there might be a problem with the connection to the server. ${truncateUrl(options.url)}`,
  164. 'error',
  165. {
  166. action: {
  167. label: 'View details',
  168. callback: () => ({
  169. request: axiosOptions,
  170. error: { message: 'Request was made but no response was received' },
  171. }),
  172. },
  173. }
  174. )
  175. }
  176. logger.log({
  177. url: axiosOptions.url,
  178. method: axiosOptions.method || 'GET',
  179. type: 'RESPONSE',
  180. description: 'No response',
  181. requestStatus: 500,
  182. requestError: error,
  183. })
  184. reject({})
  185. } else {
  186. let canceled = error.constructor.name === 'Cancel'
  187. reject({ canceled })
  188. if (canceled) {
  189. logger.log({
  190. url: axiosOptions.url,
  191. method: axiosOptions.method || 'GET',
  192. type: 'RESPONSE',
  193. requestStatus: 'canceled',
  194. })
  195. return
  196. }
  197. // Something happened in setting up the request that triggered an Error
  198. logger.log({
  199. url: axiosOptions.url,
  200. method: axiosOptions.method || 'GET',
  201. type: 'RESPONSE',
  202. description: 'Something happened in setting up the request',
  203. requestStatus: 500,
  204. })
  205. notificationStore.alert(
  206. `Request failed, there might be a problem with the connection to the server. ${truncateUrl(options.url)}`,
  207. 'error',
  208. {
  209. action: {
  210. label: 'View details',
  211. callback: () => ({
  212. request: axiosOptions,
  213. error: { message: 'Something happened in setting up the request' },
  214. }),
  215. },
  216. }
  217. )
  218. }
  219. })
  220. })
  221. }
  222. setDefaultHeader(name: string, value: ?string) {
  223. axios.defaults.headers.common[name] = value
  224. }
  225. }
  226. export default new ApiCaller()