axios.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { boot } from 'quasar/wrappers'
  2. import { Notify, Cookies } from 'quasar'
  3. import APIInstanceWrapper from 'src/api/classes/APIInstanceWrapper.js'
  4. const apiServer = process.env.APP_API
  5. const apiServerTarget = process.env.APP_API_SERVER
  6. // const apiV2Server = process.env.APP_API
  7. // const apiV2ServerTarget = process.env.APP_API_SERVER
  8. //
  9. // const apiV1Server = process.env.ALAA_API_V1
  10. // const apiV1ServerTarget = process.env.ALAA_API_V1_SERVER
  11. // const webServer = process.env.ALAA_WEB
  12. // const webServerTarget = process.env.ALAA_WEB_SERVER
  13. const AxiosHooks = (function () {
  14. let $notify = null
  15. function setNotifyInstance($q) {
  16. if (!$q.notify) {
  17. return
  18. }
  19. $notify = $q.notify
  20. }
  21. function handleErrors (error, router, store) {
  22. const messages = []
  23. if (!error || !error.response) {
  24. return
  25. }
  26. const statusCode = parseInt(error.response.status)
  27. if (statusCode >= 500 && statusCode <= 599) {
  28. messages.push('مشکلی رخ داده است. مجدد تلاش کنید.')
  29. } else if (statusCode === 404) {
  30. messages.push('موردی یافت نشد.')
  31. } else if (statusCode === 401) {
  32. const message = error.response.data.message
  33. messages.push(message)
  34. deAuthorizeUser(router, store)
  35. } else if (statusCode === 403) {
  36. const message = error.response.data.detail
  37. messages.push(message)
  38. } else if (error.response.data) {
  39. for (const key of Object.keys(error.response.data)) {
  40. if (typeof error.response.data[key] === 'string') {
  41. messages.push(key + ': ' + error.response.data[key])
  42. } else if (Array.isArray(error.response.data[key])) {
  43. error.response.data[key].forEach(message => {
  44. messages.push(key + ': ' + message)
  45. })
  46. }
  47. }
  48. }
  49. toastMessages(messages)
  50. return Promise.reject(error)
  51. }
  52. function handleFulfilled (response) {
  53. if (
  54. // response.config.method === 'get' ||
  55. // response.config.method === 'GET' ||
  56. response.config.method === 'post' ||
  57. response.config.method === 'POST' ||
  58. response.config.method === 'put' ||
  59. response.config.method === 'PUT' ||
  60. response.config.method === 'delete' ||
  61. response.config.method === 'DELETE'
  62. ) {
  63. const message = 'با موفقیت انجام شد'
  64. if ($notify) {
  65. $notify({
  66. type: 'positive',
  67. message
  68. })
  69. } else {
  70. Notify.create({
  71. type: 'positive',
  72. color: 'positive',
  73. timeout: 5000,
  74. position: 'top',
  75. message,
  76. icon: 'report_problem'
  77. })
  78. }
  79. }
  80. }
  81. function deAuthorizeUser(router, store) {
  82. store.dispatch('Auth/logOut', { redirectTo: false, clearRedirectTo: false })
  83. const loginRouteName = 'Login'
  84. const currentRoute = (router?.currentRoute?._value) ? router.currentRoute._value : (router?.history?.current) ? router.history.current : null
  85. if (currentRoute && currentRoute.name === loginRouteName) {
  86. return
  87. }
  88. store.commit('Auth/updateRedirectTo', currentRoute)
  89. router.push({ name: loginRouteName })
  90. }
  91. function toastMessages(messages) {
  92. messages.forEach((item) => {
  93. if ($notify) {
  94. $notify({
  95. type: 'negative',
  96. color: 'negative',
  97. message: item,
  98. icon: 'report_problem'
  99. })
  100. } else {
  101. Notify.create({
  102. type: 'negative',
  103. color: 'negative',
  104. timeout: 5000,
  105. position: 'top',
  106. message: item,
  107. icon: 'report_problem'
  108. })
  109. }
  110. })
  111. }
  112. return {
  113. handleErrors,
  114. handleFulfilled,
  115. setNotifyInstance
  116. }
  117. }())
  118. // Be careful when using SSR for cross-request state pollution
  119. // due to creating a Singleton instance here;
  120. // If any client changes this (global) instance, it might be a
  121. // good idea to move this instance creation inside the
  122. // "export default () => {}" function below (which runs individually
  123. // for each client)
  124. const appApi = APIInstanceWrapper.createInstance(apiServer, apiServerTarget)
  125. export default boot(({ app, store, router, ssrContext }) => {
  126. // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  127. // so you can easily perform requests against your app's API
  128. AxiosHooks.setNotifyInstance(app.config.globalProperties.$q)
  129. if (appApi.interceptors) {
  130. appApi.interceptors.response.use(function (response) {
  131. AxiosHooks.handleFulfilled(response)
  132. return Promise.resolve(response)
  133. }, async function (error) {
  134. return Promise.reject(await AxiosHooks.handleErrors(error, router, store))
  135. })
  136. }
  137. store.$axios = appApi
  138. router.$axios = appApi
  139. app.config.globalProperties.$axios = appApi
  140. const cookies = process.env.SERVER
  141. ? Cookies.parseSSR(ssrContext)
  142. : Cookies // otherwise we're on client
  143. const allCookies = cookies.getAll()
  144. const cookiesAccessTokenInCookies = cookies.get('BearerAccessToken') ? cookies.get('BearerAccessToken') : allCookies.BearerAccessToken
  145. // const cookiesAccessTokenInCookies = cookies.get('BearerAccessToken')
  146. const accessTokenInLocalStorage = store.getters['Auth/accessToken']
  147. const cookiesAccessToken = accessTokenInLocalStorage || cookiesAccessTokenInCookies
  148. if (cookiesAccessToken) {
  149. const tokenType = 'Bearer'
  150. store.$accessToken = cookiesAccessToken
  151. // const internalAxiosRequesConfig = (config) => {
  152. // config.headers.Authorization = `${tokenType} ${cookiesAccessToken}`
  153. // return config
  154. // }
  155. // const onRejectAxios = (error) => {
  156. // return Promise.reject(error)
  157. // }
  158. //
  159. // appApi.interceptors.request.use(internalAxiosRequesConfig, onRejectAxios)
  160. appApi.defaults.headers.common.Authorization = tokenType + ' ' + cookiesAccessToken
  161. // apiV1.defaults.headers.common.Authorization = tokenType + ' ' + cookiesAccessToken
  162. // apiWeb.defaults.headers.common.Authorization = tokenType + ' ' + cookiesAccessToken
  163. } else {
  164. // console.error('axios boot->Auth/logOut')
  165. store.dispatch('Auth/logOut')
  166. }
  167. })
  168. export { appApi }