dataProvider.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {AnyJson, DataProviderArgs} from "~/types/interfaces";
  2. import {DENORMALIZER_TYPE, HTTP_METHOD, QUERY_TYPE} from "~/types/enums";
  3. import {providers} from "~/services/dataProvider/provider/_import";
  4. import ConstructUrl from "~/services/connection/constructUrl";
  5. import Connection from "~/services/connection/connection";
  6. import Serializer from "~/services/serializer/serializer";
  7. import {Context} from "@nuxt/types/app";
  8. import ApiError from "~/services/utils/apiError";
  9. class DataProvider{
  10. private ctx !: Context;
  11. private arguments!: DataProviderArgs;
  12. constructor() {
  13. this.arguments = {
  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. setArguments(args: DataProviderArgs){
  23. this.arguments = { ...this.arguments, ...args }
  24. }
  25. async invoke(args:DataProviderArgs): Promise<any>{
  26. try{
  27. this.setArguments(args)
  28. this.startLoading()
  29. const url = this.constructUrl()
  30. const response = await this.connection(url)
  31. const deserializeResponse = await this.deserialization(response)
  32. return await this.provide(deserializeResponse)
  33. }catch(error){
  34. throw new ApiError(500, error)
  35. }
  36. }
  37. startLoading(){
  38. if(this.arguments.progress){
  39. const $nuxt = window['$nuxt']
  40. $nuxt.$loading.start()
  41. }
  42. }
  43. constructUrl(): string{
  44. const constructUrl = new ConstructUrl();
  45. return constructUrl.invoke(this.arguments)
  46. }
  47. connection(url: string): Promise<any>{
  48. const connection = new Connection()
  49. return connection.invoke(HTTP_METHOD.GET, url, this.arguments)
  50. }
  51. provide(data: AnyJson): any{
  52. for(const provider of providers){
  53. if(provider.support(this.arguments)){
  54. return new provider(this.ctx, this.arguments).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