import {hooks} from "~/services/dataPersister/hook/_import"; import {AnyJson, DataPersisterArgs, DataProviderArgs} from "~/types/interfaces"; import {Context} from "@nuxt/types/app"; 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 arguments: DataPersisterArgs constructor() { this.sort() this.arguments = { type: QUERY_TYPE.MODEL, progress:true } } initCtx(ctx:Context){ Connection.initConnector(ctx.$axios) this.ctx = ctx } setArguments(args: DataProviderArgs){ this.arguments = { ...this.arguments, ...args } } async invoke(args:DataPersisterArgs): Promise{ try{ this.setArguments(args) this.startLoading() this.preHook() this.arguments.data = this.serialization() const url = this.constructUrl() const response = await this.connection(url) this.provideResponse(response) }catch(error){ throw new ApiError(error.response.status, error.response.data.detail) } } startLoading(){ if(this.arguments.progress){ const $nuxt = window['$nuxt'] $nuxt.$loading.start() } } async preHook(){ for(const hook of hooks){ if(hook.support(this.arguments)){ await new hook().invoke(this.arguments) } } } serialization(){ const serializer = new Serializer() return serializer.normalize(this.arguments) } constructUrl(): string{ const constructUrl = new ConstructUrl() return constructUrl.invoke(this.arguments) } connection(url: string): Promise{ const connection = new Connection() return connection.invoke(this.arguments.id ? HTTP_METHOD.PUT : HTTP_METHOD.POST, url, this.arguments) } async provideResponse(response: AnyJson){ const dataProvider = new DataProvider() dataProvider.setArguments({ type: this.arguments.type, url: this.arguments.url, enumType: this.arguments.enumType, model: this.arguments.model, root_model: this.arguments.root_model, id: this.arguments.id, root_id: this.arguments.root_id }) const deserializeResponse = dataProvider.deserialization(response) return await dataProvider.provide(deserializeResponse) } 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