import { Context } from '@nuxt/types/app' import { hooks } from '~/services/dataPersister/hook/_import' import { AnyJson, DataPersisterArgs, DataProviderArgs } from '~/types/interfaces' import Connection from '~/services/connection/connection' import ConstructUrl from '~/services/connection/constructUrl' import { HTTP_METHOD, QUERY_TYPE } from '~/types/enums' import Serializer from '~/services/serializer/serializer' import ApiError from '~/services/utils/apiError' import DataProvider from '~/services/dataProvider/dataProvider' class DataPersister { private ctx !: Context private defaultArguments: DataPersisterArgs constructor () { this.sort() this.defaultArguments = { type: QUERY_TYPE.MODEL, progress: true } } initCtx (ctx:Context) { Connection.initConnector(ctx.$axios) this.ctx = ctx } getArguments (args: DataPersisterArgs):DataPersisterArgs { return { ...this.defaultArguments, ...args } } async invoke (args:DataPersisterArgs): Promise { try { const dpArgs = this.getArguments(args) this.startLoading(dpArgs) this.preHook(dpArgs) dpArgs.data = this.serialization(dpArgs) const url = this.constructUrl(dpArgs) const response = await this.connection(url, dpArgs) this.provideResponse(response, dpArgs) } catch (error) { throw new ApiError(error.response.status, error.response.data.detail) } } startLoading (args: DataPersisterArgs) { if (args.progress) { const $nuxt = window.$nuxt $nuxt.$loading.start() } } async preHook (args: DataPersisterArgs) { for (const hook of hooks) { if (hook.support(args)) { await new hook().invoke(args) } } } serialization (args: DataPersisterArgs) { const serializer = new Serializer() return serializer.normalize(args) } constructUrl (args: DataPersisterArgs): string { const constructUrl = new ConstructUrl() return constructUrl.invoke(args) } connection (url: string, args: DataPersisterArgs): Promise { const connection = new Connection() return connection.invoke(args.id ? HTTP_METHOD.PUT : HTTP_METHOD.POST, url, args) } async provideResponse (response: AnyJson, args: DataPersisterArgs) { const dataProvider = new DataProvider() const dataProviderArgs: DataProviderArgs = { type: args.type, url: args.url, enumType: args.enumType, model: args.model, root_model: args.root_model, id: args.id, root_id: args.root_id } const deserializeResponse = dataProvider.deserialization(response) return await dataProvider.provide(deserializeResponse, dataProviderArgs) } sort () { hooks.sort(function (a, b) { if (a.priority > b.priority) { return 1 } if (a.priority < b.priority) { return -1 } return 0 }) } } export default DataPersister