baseDataManager.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. return await this._invoke(queryArguments)
  41. }
  42. /**
  43. * Signale le début du chargement à nuxt (si showProgress est true)
  44. * @param {UrlArgs} args
  45. */
  46. private static startLoading (args: UrlArgs) {
  47. if (args.showProgress) {
  48. const $nuxt = window.$nuxt
  49. $nuxt.$loading.start()
  50. }
  51. }
  52. /**
  53. * Send the request trough the Connection
  54. * @param {string} url
  55. * @param {HTTP_METHOD} method
  56. * @param {UrlArgs} args
  57. */
  58. public static request (url: string, method: HTTP_METHOD, args: UrlArgs): Promise<any> {
  59. return Connection.invoke(method, url, args)
  60. }
  61. }
  62. export default BaseDataManager