baseDataManager.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Context } from '@nuxt/types/app'
  2. import { DataManager, UrlArgs } from '~/types/interfaces'
  3. import Connection from '~/services/connection/connection'
  4. import Hookable from '~/services/data/hookable'
  5. import { HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
  6. import ApiError from '~/services/exception/apiError'
  7. /**
  8. * Base class for data providers, persisters or deleters
  9. */
  10. abstract class BaseDataManager extends Hookable implements DataManager {
  11. protected ctx!: Context
  12. protected arguments!: UrlArgs
  13. protected defaultArguments: object = {
  14. type: QUERY_TYPE.MODEL,
  15. showProgress: true
  16. }
  17. /**
  18. * Initialise le contexte (la connection en particulier)
  19. * @param ctx
  20. */
  21. public initCtx (ctx: Context) {
  22. Connection.initConnector(ctx.$axios)
  23. this.ctx = ctx
  24. }
  25. /**
  26. * Exécute la requête et retourne la réponse désérialisée
  27. * @param _args
  28. */
  29. // eslint-disable-next-line require-await
  30. protected async _invoke (_args: UrlArgs): Promise<any> {
  31. throw new Error('Not implemented')
  32. }
  33. /**
  34. * Exécute la requête
  35. * @param args
  36. */
  37. public async invoke (args: UrlArgs): Promise<any> {
  38. this.arguments = { ...this.defaultArguments, ...args }
  39. BaseDataManager.startLoading(this.arguments)
  40. await this.triggerHooks(args)
  41. try {
  42. return this._invoke(args)
  43. } catch (error) {
  44. throw new ApiError(error.response.status, error.response.data.detail)
  45. }
  46. }
  47. /**
  48. * Signale le début du chargement à nuxt (si showProgress est true)
  49. * @param args
  50. */
  51. private static startLoading (args: UrlArgs) {
  52. if (args.showProgress) {
  53. const $nuxt = window.$nuxt
  54. $nuxt.$loading.start()
  55. }
  56. }
  57. /**
  58. * Send the request trough the Connection
  59. * @param url
  60. * @param method
  61. * @param args
  62. */
  63. protected static request (url: string, method: HTTP_METHOD, args: UrlArgs): Promise<any> {
  64. return Connection.invoke(method, url, args)
  65. }
  66. }
  67. export default BaseDataManager