baseDataManager.ts 1.9 KB

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