| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import { Context } from '@nuxt/types/app'
- import { AnyJson, DataProviderArgs } from '~/types/interfaces'
- import { DENORMALIZER_TYPE, HTTP_METHOD, QUERY_TYPE } from '~/types/enums'
- import { providers } from '~/services/dataProvider/provider/_import'
- import ConstructUrl from '~/services/connection/constructUrl'
- import Connection from '~/services/connection/connection'
- import Serializer from '~/services/serializer/serializer'
- import ApiError from '~/services/utils/apiError'
- class DataProvider {
- private ctx !: Context;
- private defaultArguments!: DataProviderArgs;
- constructor () {
- this.defaultArguments = {
- type: QUERY_TYPE.MODEL,
- progress: false
- }
- }
- initCtx (ctx:Context) {
- Connection.initConnector(ctx.$axios)
- this.ctx = ctx
- }
- getArguments (args: DataProviderArgs): DataProviderArgs {
- return { ...this.defaultArguments, ...args }
- }
- async invoke (args:DataProviderArgs): Promise<any> {
- try {
- const dpArgs = this.getArguments(args)
- this.startLoading(dpArgs)
- const url = this.constructUrl(dpArgs)
- const response = await this.connection(url, dpArgs)
- const deserializeResponse = await this.deserialization(response)
- return await this.provide(deserializeResponse, dpArgs)
- } catch (error) {
- throw new ApiError(500, error)
- }
- }
- startLoading (args: DataProviderArgs) {
- if (args.progress) {
- const $nuxt = window.$nuxt
- $nuxt.$loading.start()
- }
- }
- constructUrl (args: DataProviderArgs): string {
- const constructUrl = new ConstructUrl()
- return constructUrl.invoke(args)
- }
- connection (url: string, args: DataProviderArgs): Promise<any> {
- const connection = new Connection()
- return connection.invoke(HTTP_METHOD.GET, url, args)
- }
- provide (data: AnyJson, args: DataProviderArgs): any {
- for (const provider of providers) {
- if (provider.support(args)) {
- return new provider(this.ctx, args).invoke(data)
- }
- }
- }
- deserialization (data: AnyJson): AnyJson {
- const serializer = new Serializer()
- return serializer.denormalize(data, DENORMALIZER_TYPE.HYDRA)
- }
- }
- export default DataProvider
|