baseDataManager.ts 2.1 KB

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