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. /**
  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. const response = await this._invoke(queryArguments)
  39. await this.triggerHooks(queryArguments)
  40. return response
  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