| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- import {hooks} from "~/services/dataPersister/hook/_import";
- import {AnyJson, DataPersisterArgs} from "~/types/interfaces";
- import {Context} from "@nuxt/types/app";
- import Connection from "~/services/connection/connection";
- import ConstructUrl from "~/services/connection/constructUrl";
- import {HTTP_METHOD} 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()
- }
- initCtx(ctx:Context){
- Connection.initConnector(ctx.$axios)
- this.ctx = ctx
- }
- async invoke(args:DataPersisterArgs): Promise<any>{
- this.arguments = args
- try{
- 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)
- }
- }
- 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
|