connection.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import {AnyJson, DataPersisterArgs, DataProviderArgs, UrlArgs} from '~/types/interfaces'
  2. import {HTTP_METHOD, QUERY_TYPE} from '~/types/enums'
  3. import TypesTesting from "~/services/utils/typesTesting";
  4. import {$fetch, FetchOptions} from "ohmyfetch";
  5. import {useProfileAccessStore} from "~/store/profile/access";
  6. import Page from "~//services/store/page";
  7. import {TYPE_ALERT} from "~//types/enums";
  8. /**
  9. * @category Services/connection
  10. * @class Connection
  11. *
  12. * Classe Wrapper du connecteur de requête (Axios dans notre cas)
  13. */
  14. class Connection {
  15. /**
  16. * Main méthode qui appellera les méthodes privées correspondantes (getItem, getCollection, put, post, delete)
  17. * @param {HTTP_METHOD} method Mode de requêtage (GET, PUT, DELETE...)
  18. * @param {string} url
  19. * @param {DataProviderArgs|DataPersisterArgs} args
  20. * @return {Promise<any>}
  21. */
  22. public static invoke (method: HTTP_METHOD, url: string, args: UrlArgs): Promise<any> {
  23. switch (method) {
  24. case HTTP_METHOD.GET:
  25. if (args.type === QUERY_TYPE.FILE) {
  26. return Connection.download(url, args.showProgress, args.params)
  27. }
  28. if (args.id) {
  29. return Connection.getItem(url, args.id, args.showProgress, args.params)
  30. } else {
  31. return Connection.getCollection(url, args.type, args.showProgress, args.params)
  32. }
  33. case HTTP_METHOD.PUT:
  34. case HTTP_METHOD.POST:
  35. if (!TypesTesting.isDataPersisterArgs(args)) {
  36. throw new Error('*args* is not a dataPersisterArgs')
  37. }
  38. if (!args.data) {
  39. throw new Error('*args* has no data')
  40. }
  41. switch (method) {
  42. case HTTP_METHOD.PUT:
  43. return Connection.put(url, args.id, args.data, args.showProgress, args.params)
  44. case HTTP_METHOD.POST:
  45. return Connection.post(url, args.data, args.showProgress, args.params)
  46. }
  47. break;
  48. case HTTP_METHOD.DELETE:
  49. return Connection.deleteItem(url, args.id, args.showProgress, args.params)
  50. }
  51. throw new Error('Unknown connection method was invoked')
  52. }
  53. /**
  54. * GET Item : préparation de la config pour la récupération d'un item
  55. * @param {string} url
  56. * @param {number} id
  57. * @param {boolean} showProgress
  58. * @param {AnyJson} params
  59. * @return {Promise<any>}
  60. */
  61. public static getItem (url: string, id: number, showProgress: boolean = true, params: AnyJson = {}): Promise<any> {
  62. const config: FetchOptions = {
  63. method: HTTP_METHOD.GET,
  64. progress: showProgress,
  65. params: params
  66. }
  67. return Connection.request(`${url}/${id}`, config)
  68. }
  69. /**
  70. * Get collection : préparation de la config pour la récupération d'une collection d'items
  71. * @param {string} url
  72. * @param {boolean} progress
  73. * @param {QUERY_TYPE} type
  74. * @param {AnyJson} params
  75. * @return {Promise<any>}
  76. */
  77. public static getCollection (url: string, type: QUERY_TYPE, progress: boolean = true, params: AnyJson = {}): Promise<any> {
  78. let config: FetchOptions = {
  79. method: HTTP_METHOD.GET,
  80. progress,
  81. params: params
  82. }
  83. if(type === QUERY_TYPE.IMAGE)
  84. config = {...config, responseType: 'blob'}
  85. return Connection.request(`${url}`, config)
  86. }
  87. /**
  88. * GET dédié au téléchargement de fichiers
  89. * @param url
  90. * @param {number} id
  91. * @param {boolean} showProgress
  92. * @param {AnyJson} params
  93. * @return {Promise<any>}
  94. */
  95. public static download (url: string, showProgress: boolean = true, params: AnyJson = {}): Promise<any> {
  96. const config: FetchOptions = {
  97. method: HTTP_METHOD.GET,
  98. progress: showProgress,
  99. responseType: 'blob',
  100. params: params
  101. }
  102. return Connection.request(`${url}`, config)
  103. }
  104. /**
  105. * Post : préparation de la config pour la création d'un item
  106. * @param {string} url
  107. * @param {AnyJson} data
  108. * @param {boolean} progress
  109. * @param {AnyJson} params
  110. * @return {Promise<any>}
  111. */
  112. public static post(url: string, data: AnyJson, progress: boolean = true, params: AnyJson = {}): Promise<any> {
  113. const config: FetchOptions = {
  114. method: HTTP_METHOD.POST,
  115. data,
  116. progress,
  117. params: params
  118. }
  119. return Connection.request(`${url}`, config)
  120. }
  121. /**
  122. * Put : préparation de la config pour la mise à jour d'un item
  123. * @param {string} url
  124. * @param {number} id
  125. * @param {AnyJson} data
  126. * @param {boolean} progress
  127. * @param {AnyJson} params
  128. * @return {Promise<any>}
  129. */
  130. public static put (url: string, id: number, data: AnyJson, progress: boolean = true, params: AnyJson = {}): Promise<any> {
  131. const config: FetchOptions = {
  132. method: HTTP_METHOD.PUT,
  133. data,
  134. progress,
  135. params: params
  136. }
  137. return Connection.request(`${url}/${id}`, config)
  138. }
  139. /**
  140. * DELETE Item : préparation de la config pour la suppression d'un item
  141. * @param {string} url
  142. * @param {number} id
  143. * @param {boolean} progress
  144. * @param {AnyJson} params
  145. * @return {Promise<any>}
  146. */
  147. public static deleteItem (url: string, id: number, progress: boolean = true, params: AnyJson = {}): Promise<any> {
  148. const config: FetchOptions = {
  149. method: HTTP_METHOD.DELETE,
  150. progress,
  151. params: params
  152. }
  153. return Connection.request(`${url}/${id}`, config)
  154. }
  155. /**
  156. * Exécute la requete
  157. * @param {string} url
  158. * @param {FetchOptions} config
  159. * @return {Promise<any>}
  160. */
  161. public static async request (url: string, config: FetchOptions): Promise<FetchResponse> {
  162. Connection.addBaseUrl(config)
  163. Connection.addHeader(config)
  164. Connection.addOnResponseError(config)
  165. return await $fetch(url, config)
  166. }
  167. /**
  168. * On ajoute la base URL
  169. * @param config
  170. */
  171. public static addBaseUrl(config){
  172. const runtimeConfig = useRuntimeConfig()
  173. config['baseURL'] = runtimeConfig.baseUrl ?? runtimeConfig.public.baseUrl
  174. }
  175. /**
  176. * On ajoute les headers
  177. * @param config
  178. */
  179. public static addHeader(config){
  180. if(!config.params.noXaccessId){
  181. const profileAccessStore = useProfileAccessStore()
  182. config['headers'] = {
  183. 'x-accessid' : profileAccessStore.id,
  184. 'Authorization' : 'BEARER ' + profileAccessStore.bearer
  185. }
  186. if (profileAccessStore.switchId) {
  187. config['headers']['x-switch-user'] = profileAccessStore.switchId
  188. }
  189. }
  190. }
  191. /**
  192. * Gestion des erreurs de réponse
  193. * @param config
  194. */
  195. public static async addOnResponseError(config){
  196. config['onResponseError'] = (({ request, response, options }) => {
  197. // In case of unauthorized, redirect to a specific page
  198. if (response.status === 401) {
  199. redirect('/login')
  200. }
  201. if (response.status === 403) {
  202. new Page().addAlerts(TYPE_ALERT.ALERT, ['forbidden'])
  203. }
  204. if (response.status === 500) {
  205. new Page().addAlerts(TYPE_ALERT.ALERT, [response])
  206. }
  207. })
  208. }
  209. }
  210. export default Connection