| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318 |
- import ApiRequestService from "./apiRequestService";
- import {Repository, useRepo} from "pinia-orm";
- import Url from "~/services/utils/url";
- import ModelNormalizer from "./serializer/normalizer/modelNormalizer";
- import HydraDenormalizer from "./serializer/denormalizer/hydraDenormalizer";
- import ApiModel from "~/models/ApiModel";
- import {useAccessProfileStore} from "~/store/profile/access";
- import ApiResource from "~/models/ApiResource";
- import {MyProfile} from "~/models/Access/MyProfile";
- import { v4 as uuid4 } from 'uuid';
- import {AssociativeArray, Collection} from "~/types/data.d";
- import {useCloneDeep} from "#imports";
- /**
- * Entity manager: make operations on the models defined with the Pinia-Orm library
- *
- * @see https://pinia-orm.codedredd.de/
- */
- class EntityManager {
- private CLONE_PREFIX = '_clone_'
- private apiRequestService: ApiRequestService
- public constructor(
- apiRequestService: ApiRequestService
- ) {
- this.apiRequestService = apiRequestService
- }
- /**
- * Return the repository for the model
- *
- * @param model
- */
- public getRepository(model: typeof ApiResource): Repository<ApiResource> {
- return useRepo(model)
- }
- // noinspection JSMethodCanBeStatic
- public cast(model: typeof ApiResource, entity: ApiResource): ApiResource {
- return new model(entity)
- }
- /**
- * Create a new instance of the given model
- *
- * @param model
- * @param properties
- */
- public newInstance(model: typeof ApiResource, properties: object = {}): ApiResource {
- const repository = this.getRepository(model)
- let entity = repository.make(properties)
- entity.setModel(model)
- // @ts-ignore
- if (!properties.hasOwnProperty('id') || !properties.id) {
- // Object has no id yet, we give him a temporary one
- entity.id = 'tmp' + uuid4()
- }
- entity = repository.save(entity)
- this.saveInitialState(model, entity)
- return entity
- }
- /**
- * Save the entity into the store
- *
- * @param model
- * @param entity
- */
- public save(model: typeof ApiResource, entity: ApiResource): ApiResource {
- return this.getRepository(model).save(entity)
- }
- /**
- * Find the entity into the store
- *
- * @param model
- * @param id
- */
- // @ts-ignore
- public find<T extends ApiResource>(model: typeof T, id: number): T {
- const repository = this.getRepository(model)
- return repository.find(id) as T
- }
- /**
- * Fetch an Entity / ApiResource by its id, save it to the store and returns it
- *
- * @param model Model of the object to fetch
- * @param id Id of the object to fetch
- * @param forceRefresh Force a new get request to the api ;
- * current object in store will be overwritten if it exists
- */
- public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
- const repository = this.getRepository(model)
- // If the entity is already in the store and forceRefresh is false, return the object in store
- if (!forceRefresh) {
- const item = repository.find(id)
- if (item && typeof item !== 'undefined') {
- return item
- }
- }
- // Else, get the object from the API
- const url = Url.join('api', model.entity, String(id))
- const response = await this.apiRequestService.get(url)
- // deserialize the response
- const attributes = HydraDenormalizer.denormalize(response).data as object
- return this.newInstance(model, attributes)
- }
- /**
- * Fetch a collection of entity
- * The content of `query` is converted into a query-string in the request URL
- *
- * @param model
- * @param query
- * @param parent
- */
- public async fetchCollection(model: typeof ApiResource, parent: ApiResource | null, query: AssociativeArray = []): Promise<Collection> {
- let url
- if (parent !== null) {
- url = Url.join('api', parent.entity, '' + parent.id, model.entity)
- } else {
- url = Url.join('api', model.entity)
- }
- const response = await this.apiRequestService.get(url, query)
- // deserialize the response
- const apiCollection = HydraDenormalizer.denormalize(response)
- const items = apiCollection.data.map((attributes: object) => {
- return this.newInstance(model, attributes)
- })
- return {
- items,
- totalItems: apiCollection.metadata.totalItems,
- pagination: {
- first: apiCollection.metadata.firstPage || 1,
- last: apiCollection.metadata.lastPage || 1,
- next: apiCollection.metadata.nextPage || undefined,
- previous: apiCollection.metadata.previousPage || undefined,
- }
- }
- }
- /**
- * Persist the entity as it is in the store into the data source via the API
- *
- * @param model
- * @param entity
- */
- public async persist(model: typeof ApiModel, entity: ApiModel) {
- const repository = this.getRepository(model)
- // Recast in case class definition has been "lost"
- entity = this.cast(model, entity)
- let url = Url.join('api', model.entity)
- let response
- const data = ModelNormalizer.normalize(entity)
- if (!entity.isNew()) {
- url = Url.join(url, String(entity.id))
- response = await this.apiRequestService.put(url, data)
- } else {
- delete data.id
- response = await this.apiRequestService.post(url, data)
- }
- const hydraResponse = await HydraDenormalizer.denormalize(response)
- const returnedEntity = this.newInstance(model, hydraResponse.data)
- this.saveInitialState(model, returnedEntity)
- // Save data into the store
- repository.save(returnedEntity)
- if (['accesses', 'organizations', 'parameters', 'subdomains'].includes(model.entity)) {
- await this.refreshProfile()
- }
- return returnedEntity
- }
- /**
- * Delete the entity from the datasource via the API
- *
- * @param model
- * @param entity
- */
- public async delete(model: typeof ApiModel, entity: ApiResource) {
- const repository = this.getRepository(model)
- // If object has been persisted to the datasource, send a delete request
- if (!entity.isNew()) {
- const url = Url.join('api', model.entity, String(entity.id))
- await this.apiRequestService.delete(url)
- }
- // reactiveUpdate the store
- repository.destroy(entity.id)
- }
- /**
- * Reset the entity to its initial state (i.e. the state it had when it was fetched from the API)
- *
- * @param model
- * @param entity
- */
- public reset(model: typeof ApiResource, entity: ApiResource) {
- const initialEntity = this.getInitialStateOf(model, entity.id)
- if (initialEntity === null) {
- throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + entity.id + ']')
- }
- const repository = this.getRepository(model)
- repository.save(initialEntity)
- return initialEntity
- }
- /**
- * Re-fetch the user profile and reactiveUpdate the store
- */
- public async refreshProfile() {
- const response = await this.apiRequestService.get('api/my_profile')
- // deserialize the response
- const hydraResponse = await HydraDenormalizer.denormalize(response)
- const profile = this.newInstance(MyProfile, hydraResponse.data)
- const accessProfileStore = useAccessProfileStore()
- accessProfileStore.setProfile(profile)
- }
- /**
- * Delete all records in the repository of the model
- *
- * @param model
- */
- public async flush(model: typeof ApiModel) {
- const repository = this.getRepository(model)
- repository.flush()
- }
- /**
- * Is the entity a new one, or does it already exist in the data source (=API)
- *
- * @param model
- * @param id
- */
- public isNewEntity(model: typeof ApiModel, id: number | string): boolean {
- const repository = this.getRepository(model)
- const item = repository.find(id)
- if (!item || typeof item === 'undefined') {
- console.error(model.entity + '/' + id, ' does not exist!')
- return false
- }
- return item.isNew()
- }
- /**
- * Save the state of the entity in the store, so this state could be be restored later
- *
- * @param model
- * @param entity
- * @private
- */
- private saveInitialState(model: typeof ApiResource, entity: ApiResource) {
- const repository = this.getRepository(model)
- // Clone and prefix id
- const clone = useCloneDeep(entity)
- clone.id = this.CLONE_PREFIX + clone.id
- repository.save(clone)
- }
- /**
- * Return the saved state of the entity from the store
- *
- * @param model
- * @param id
- * @private
- */
- private getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
- const repository = this.getRepository(model)
- // Find the clone by id
- const entity = repository.find(this.CLONE_PREFIX + id)
- if (entity === null) {
- return null
- }
- // Restore the initial id
- entity.id = id
- return entity
- }
- }
- export default EntityManager
|