dataManager.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { Context } from '@nuxt/types/app'
  2. import { UrlArgs } from '~/types/interfaces'
  3. import Connection from '~/services/connection/connection'
  4. import Hookable from '~/services/hooks/hookable'
  5. import { HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
  6. /**
  7. * Base class for data providers, persisters or deleters
  8. */
  9. class DataManager extends Hookable {
  10. protected ctx!: Context
  11. protected arguments!: UrlArgs
  12. protected defaultArguments: object = {
  13. type: QUERY_TYPE.MODEL,
  14. showProgress: true
  15. }
  16. /**
  17. * Initialise le contexte (la connection en particulier)
  18. * @param ctx
  19. */
  20. public initCtx (ctx: Context) {
  21. Connection.initConnector(ctx.$axios)
  22. this.ctx = ctx
  23. }
  24. /**
  25. * Exécute la requête
  26. * @param args
  27. */
  28. public async invoke (args: UrlArgs): Promise<any> {
  29. args = { ...this.defaultArguments, ...args }
  30. DataManager.startLoading(args)
  31. await this.triggerHooks(args)
  32. }
  33. /**
  34. * Signale le début du chargement à nuxt (si showProgress est true)
  35. * @param args
  36. */
  37. private static startLoading (args: UrlArgs) {
  38. if (args.showProgress) {
  39. const $nuxt = window.$nuxt
  40. $nuxt.$loading.start()
  41. }
  42. }
  43. /**
  44. * Send the request trough the Connection
  45. * @param url
  46. * @param method
  47. * @param args
  48. */
  49. protected static sendRequest (url: string, method: HTTP_METHOD, args: UrlArgs): Promise<any> {
  50. return Connection.invoke(method, url, args)
  51. }
  52. }
  53. export default DataManager