baseDataManager.ts 2.0 KB

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