| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- 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 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<any>{
- 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<any>{
- 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
|