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