axios.js 6.5 KB

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