import {repositoryHelper} from "~/services/store/repository"; import {QUERY_TYPE} from "~/types/enums"; import {computed} from '@nuxtjs/composition-api' import {accessState, AnyJson, AnyStore} from "~/types/interfaces"; import DataPersister from "~/services/dataPersister/dataPersister"; import {MyProfile} from "~/models/Access/MyProfile"; /** * @category Use/updater * @class UseMyProfileUpdater * Use Classe pour la gestion REST de MyProfile */ export class UseMyProfileUpdater{ private store!:AnyStore private $dataPersister!:DataPersister private myProfile!:MyProfile constructor(store:AnyStore, $dataPersister:DataPersister){ this.store = store this.$dataPersister = $dataPersister } /** * Composition function */ public invoke(): AnyJson{ this.myProfile = this.createNewMyProfileInstance(this.store.state.profile.access) const activityYear = computed(()=>this.myProfile.activityYear) const historical = computed(()=>this.myProfile.historical) return { updateMyProfile: () => this.updateMyProfile(), setActivityYear: (activityYear:number) => this.setActivityYear(activityYear), setHistorical: (historicalChoices:Array) => this.setHistorical(historicalChoices), activityYear, historical } } /** * Créer une nouvelle instance MyProfile * @param myProfile */ private createNewMyProfileInstance(myProfile:accessState): MyProfile{ const myProfileInstance = repositoryHelper.createNewModelInstance(MyProfile) as MyProfile myProfileInstance.id = myProfile.id myProfileInstance.activityYear = myProfile.activityYear myProfileInstance.historical = myProfile.historical repositoryHelper.persist(MyProfile, myProfileInstance) return myProfileInstance } /** * Mets à jour l'activity de my profile * @param activityYear */ private setActivityYear(activityYear:number){ if(activityYear <= 0) throw new Error('year must be positive') repositoryHelper.updateStoreFromField(MyProfile, this.myProfile, activityYear, 'activityYear') } /** * Mets à jour l'historical de my profile * @param historicalChoices */ private setHistorical(historicalChoices:Array){ repositoryHelper.updateStoreFromField(MyProfile, this.myProfile, this.getHistoricalEntry(historicalChoices), 'historical') } /** * Transform les choix de l'historique en objet JSON reconnaissable coté API * @param historicalChoices */ private getHistoricalEntry(historicalChoices:Array){ const historicalDefault:any = {'past':false, 'future':false, 'present':false} for(const historicalChoice of historicalChoices){ historicalDefault[historicalChoice] = true } return historicalDefault; } /** * Effectue la mise à jour (coté API) de MyProfile */ private async updateMyProfile(): Promise{ await this.$dataPersister.invoke({ type: QUERY_TYPE.MODEL, model: MyProfile, id: this.myProfile.id }) } } export const $useMyProfileUpdater = (store:AnyStore, $dataPersister:DataPersister) => new UseMyProfileUpdater(store, $dataPersister).invoke()