dataProvider.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Context } from '@nuxt/types/app'
  2. import { AnyJson, DataProviderArgs } from '~/types/interfaces'
  3. import { DENORMALIZER_TYPE, HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
  4. import { providers } from '~/services/dataProvider/provider/_import'
  5. import ConstructUrl from '~/services/connection/constructUrl'
  6. import Connection from '~/services/connection/connection'
  7. import Serializer from '~/services/serializer/serializer'
  8. import ApiError from '~/services/utils/apiError'
  9. class DataProvider {
  10. private ctx !: Context;
  11. private defaultArguments!: DataProviderArgs;
  12. constructor () {
  13. this.defaultArguments = {
  14. type: QUERY_TYPE.MODEL,
  15. progress: false
  16. }
  17. }
  18. initCtx (ctx:Context) {
  19. Connection.initConnector(ctx.$axios)
  20. this.ctx = ctx
  21. }
  22. getArguments (args: DataProviderArgs): DataProviderArgs {
  23. return { ...this.defaultArguments, ...args }
  24. }
  25. async invoke (args:DataProviderArgs): Promise<any> {
  26. try {
  27. const dpArgs = this.getArguments(args)
  28. this.startLoading(dpArgs)
  29. const url = this.constructUrl(dpArgs)
  30. const response = await this.connection(url, dpArgs)
  31. const deserializeResponse = await this.deserialization(response)
  32. return await this.provide(deserializeResponse, dpArgs)
  33. } catch (error) {
  34. throw new ApiError(500, error)
  35. }
  36. }
  37. startLoading (args: DataProviderArgs) {
  38. if (args.progress) {
  39. const $nuxt = window.$nuxt
  40. $nuxt.$loading.start()
  41. }
  42. }
  43. constructUrl (args: DataProviderArgs): string {
  44. const constructUrl = new ConstructUrl()
  45. return constructUrl.invoke(args)
  46. }
  47. connection (url: string, args: DataProviderArgs): Promise<any> {
  48. const connection = new Connection()
  49. return connection.invoke(HTTP_METHOD.GET, url, args)
  50. }
  51. provide (data: AnyJson, args: DataProviderArgs): any {
  52. for (const provider of providers) {
  53. if (provider.support(args)) {
  54. return new provider(this.ctx, args).invoke(data)
  55. }
  56. }
  57. }
  58. deserialization (data: AnyJson): AnyJson {
  59. const serializer = new Serializer()
  60. return serializer.denormalize(data, DENORMALIZER_TYPE.HYDRA)
  61. }
  62. }
  63. export default DataProvider