entityManager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import ApiRequestService from "./apiRequestService";
  2. import {Repository, useRepo} from "pinia-orm";
  3. import Url from "~/services/utils/url";
  4. import ModelNormalizer from "./serializer/normalizer/modelNormalizer";
  5. import HydraDenormalizer from "./serializer/denormalizer/hydraDenormalizer";
  6. import ApiModel from "~/models/ApiModel";
  7. import ApiResource from "~/models/ApiResource";
  8. import {MyProfile} from "~/models/Access/MyProfile";
  9. import {v4 as uuid4} from 'uuid';
  10. import {AssociativeArray, Collection} from "~/types/data.d";
  11. import models from "~/models/models";
  12. import {useAccessProfileStore} from "~/stores/accessProfile";
  13. /**
  14. * Entity manager: make operations on the models defined with the Pinia-Orm library
  15. *
  16. * @see https://pinia-orm.codedredd.de/
  17. */
  18. class EntityManager {
  19. private CLONE_PREFIX = '_clone_'
  20. private apiRequestService: ApiRequestService
  21. public constructor(
  22. apiRequestService: ApiRequestService
  23. ) {
  24. this.apiRequestService = apiRequestService
  25. }
  26. /**
  27. * Return the repository for the model
  28. *
  29. * @param model
  30. */
  31. public getRepository(model: typeof ApiResource): Repository<ApiResource> {
  32. return useRepo(model)
  33. }
  34. // noinspection JSMethodCanBeStatic
  35. private cast(model: typeof ApiResource, entity: ApiResource): ApiResource {
  36. return new model(entity)
  37. }
  38. /**
  39. * Return the model class with the given entity name
  40. *
  41. * @param entityName
  42. */
  43. public getModelFor(entityName: string): typeof ApiResource {
  44. return models[entityName]
  45. }
  46. /**
  47. * Return the model class from an Opentalent Api IRI
  48. *
  49. * @param iri An IRI of the form .../api/<entity>/...
  50. */
  51. public getModelFromIri(iri: string): typeof ApiResource {
  52. const matches = iri.match(/^\/api\/(\w+)\/.*/)
  53. if (!matches || !matches[1]) {
  54. throw new Error('cannot parse the IRI')
  55. }
  56. return this.getModelFor(matches[1])
  57. }
  58. /**
  59. * Create a new instance of the given model
  60. *
  61. * @param model
  62. * @param properties
  63. */
  64. public newInstance(model: typeof ApiResource, properties: object = {}): ApiResource {
  65. const repository = this.getRepository(model)
  66. //@todo : make renvoi un model donc peut etre une confusion ?
  67. //@todo: pourquoi faire un make ? pourquoi ne pas utiliser le new ? En plus si les propriétés ne sont pas nulles, on peut directement passer au save
  68. let entity = repository.make(properties)
  69. // Keep track of the entitie's model
  70. entity.setModel(model)
  71. // @ts-ignore
  72. if (!properties.hasOwnProperty('id') || !properties.id) {
  73. // Object has no id yet, we give him a temporary one
  74. entity.id = 'tmp' + uuid4()
  75. }
  76. entity = repository.save(entity)
  77. this.saveInitialState(model, entity)
  78. return entity
  79. }
  80. /**
  81. * Save the entity into the store
  82. *
  83. * @param model
  84. * @param entity
  85. */
  86. public save(model: typeof ApiResource, entity: ApiResource): ApiResource {
  87. return this.getRepository(model).save(entity)
  88. }
  89. /**
  90. * Find the entity into the store
  91. *
  92. * @param model
  93. * @param id
  94. */
  95. // @ts-ignore
  96. public find<T extends ApiResource>(model: typeof T, id: number): T {
  97. const repository = this.getRepository(model)
  98. return repository.find(id) as T
  99. }
  100. /**
  101. * Fetch an Entity / ApiResource by its id, save it to the store and returns it
  102. *
  103. * @param model Model of the object to fetch
  104. * @param id Id of the object to fetch
  105. * @param forceRefresh Force a new get request to the api ;
  106. * current object in store will be overwritten if it exists
  107. */
  108. public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
  109. // If the entity is already in the store and forceRefresh is false, return the object in store
  110. if (!forceRefresh) {
  111. const item = this.find(model, id)
  112. if (item && typeof item !== 'undefined') {
  113. return item
  114. }
  115. }
  116. // Else, get the object from the API
  117. const url = Url.join('api', model.entity, String(id))
  118. const response = await this.apiRequestService.get(url)
  119. // deserialize the response
  120. const attributes = HydraDenormalizer.denormalize(response).data as object
  121. return this.newInstance(model, attributes)
  122. }
  123. /**
  124. * @todo: avec la nouvelle version de API Platform ça va pas mal avec la nouvelle gestion des sous resources...
  125. * Fetch a collection of entity
  126. * The content of `query` is converted into a query-string in the request URL
  127. *
  128. * @param model
  129. * @param query
  130. * @param parent
  131. */
  132. public async fetchCollection(model: typeof ApiResource, parent: ApiResource | null, query: AssociativeArray = []): Promise<Collection> {
  133. let url
  134. if (parent !== null) {
  135. url = Url.join('api', parent.entity, '' + parent.id, model.entity)
  136. } else {
  137. url = Url.join('api', model.entity)
  138. }
  139. const response = await this.apiRequestService.get(url, query)
  140. // deserialize the response
  141. const apiCollection = HydraDenormalizer.denormalize(response)
  142. //@todo: le map ne doit pas être nécessaire car on peut passer directement une collection au save.
  143. const items = apiCollection.data.map((attributes: object) => {
  144. return this.newInstance(model, attributes)
  145. })
  146. return {
  147. items,
  148. totalItems: apiCollection.metadata.totalItems,
  149. pagination: {
  150. first: apiCollection.metadata.firstPage || 1,
  151. last: apiCollection.metadata.lastPage || 1,
  152. next: apiCollection.metadata.nextPage || undefined,
  153. previous: apiCollection.metadata.previousPage || undefined,
  154. }
  155. }
  156. }
  157. private async saveResponseAsEntity(model: typeof ApiModel, response: Response) {
  158. const repository = this.getRepository(model)
  159. const hydraResponse = await HydraDenormalizer.denormalize(response)
  160. const returnedEntity = this.newInstance(model, hydraResponse.data)
  161. this.saveInitialState(model, returnedEntity)
  162. // Save data into the store
  163. repository.save(returnedEntity)
  164. return returnedEntity
  165. }
  166. /**
  167. * Persist the entity as it is in the store into the data source via the API
  168. *
  169. * @param model
  170. * @param entity
  171. */
  172. public async persist(model: typeof ApiModel, entity: ApiModel) {
  173. // Recast in case class definition has been "lost"
  174. entity = this.cast(model, entity)
  175. let url = Url.join('api', model.entity)
  176. let response
  177. const data = ModelNormalizer.normalize(entity)
  178. if (!entity.isNew()) {
  179. url = Url.join(url, String(entity.id))
  180. response = await this.apiRequestService.put(url, data)
  181. } else {
  182. delete data.id
  183. response = await this.apiRequestService.post(url, data)
  184. }
  185. const createdEntity = this.saveResponseAsEntity(model, response)
  186. if (entity.isNew()) {
  187. this.removeTempAfterPersist(model, entity.id)
  188. }
  189. return createdEntity
  190. }
  191. /**
  192. * Send an update request (PUT) to the API with the given data on an existing entity
  193. *
  194. * @param model
  195. * @param id
  196. * @param data
  197. */
  198. public async patch(model: typeof ApiModel, id: number, data: AssociativeArray) {
  199. let url = Url.join('api', model.entity, ''+id)
  200. const body = JSON.stringify(data)
  201. const response = await this.apiRequestService.put(url, body)
  202. return this.saveResponseAsEntity(model, response)
  203. }
  204. /**
  205. * Delete the entity from the datasource via the API
  206. *
  207. * @param model
  208. * @param entity
  209. */
  210. public async delete(model: typeof ApiModel, entity: ApiResource) {
  211. const repository = this.getRepository(model)
  212. // If object has been persisted to the datasource, send a delete request
  213. if (!entity.isNew()) {
  214. const url = Url.join('api', model.entity, String(entity.id))
  215. await this.apiRequestService.delete(url)
  216. }
  217. // reactiveUpdate the store
  218. repository.destroy(entity.id)
  219. }
  220. /**
  221. * Reset the entity to its initial state (i.e. the state it had when it was fetched from the API)
  222. *
  223. * @param model
  224. * @param entity
  225. */
  226. public reset(model: typeof ApiResource, entity: ApiResource) {
  227. const initialEntity = this.getInitialStateOf(model, entity.id)
  228. if (initialEntity === null) {
  229. throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + entity.id + ']')
  230. }
  231. const repository = this.getRepository(model)
  232. repository.save(initialEntity)
  233. return initialEntity
  234. }
  235. /**
  236. * @todo: à déplacer dans le store directement
  237. * @Deprecated : a priori ce n'est pas le bon service pour mettre à jour le profil, on devrait voir ça
  238. * depuis un service dédié, un composable, ou directement dans le store ==> oui !
  239. *
  240. * Re-fetch the user profile and update the store
  241. */
  242. public async refreshProfile(accessId: number) {
  243. const profile = await this.fetch(MyProfile, accessId)
  244. // On met à jour le store accessProfile
  245. const accessProfileStore = useAccessProfileStore()
  246. accessProfileStore.setProfile(profile)
  247. }
  248. /**
  249. * Delete all records in the repository of the model
  250. *
  251. * @param model
  252. */
  253. public async flush(model: typeof ApiModel) {
  254. const repository = this.getRepository(model)
  255. repository.flush()
  256. }
  257. /**
  258. * Is the entity a new one, or does it already exist in the data source (=API)
  259. *
  260. * @param model
  261. * @param id
  262. */
  263. public isNewEntity(model: typeof ApiModel, id: number | string): boolean {
  264. const repository = this.getRepository(model)
  265. const item = repository.find(id)
  266. if (!item || typeof item === 'undefined') {
  267. console.error(model.entity + '/' + id, ' does not exist!')
  268. return false
  269. }
  270. return item.isNew()
  271. }
  272. /**
  273. * Save the state of the entity in the store, so this state could be be restored later
  274. *
  275. * @param model
  276. * @param entity
  277. * @private
  278. */
  279. private saveInitialState(model: typeof ApiResource, entity: ApiResource) {
  280. const repository = this.getRepository(model)
  281. // Clone and prefix id
  282. const clone = useCloneDeep(entity)
  283. clone.id = this.CLONE_PREFIX + clone.id
  284. repository.save(clone)
  285. }
  286. /**
  287. * Return the saved state of the entity from the store
  288. *
  289. * @param model
  290. * @param id
  291. * @private
  292. */
  293. private getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
  294. const repository = this.getRepository(model)
  295. // Find the clone by id
  296. const entity = repository.find(this.CLONE_PREFIX + id)
  297. if (entity === null) {
  298. return null
  299. }
  300. // Restore the initial id
  301. entity.id = id
  302. return entity
  303. }
  304. /**
  305. * Delete the temporary entity from the repo after it was persisted via the api, replaced by the entity
  306. * that has been returned by the api with is definitive id.
  307. *
  308. * @param model
  309. * @param tempEntityId
  310. * @private
  311. */
  312. private removeTempAfterPersist(model: typeof ApiResource, tempEntityId: number) {
  313. const repository = this.getRepository(model)
  314. const entity = repository.find(tempEntityId)
  315. if (!entity || typeof entity === 'undefined') {
  316. console.error(model.entity + '/' + tempEntityId, ' does not exist!')
  317. return
  318. }
  319. if (!entity.isNew()) {
  320. throw new Error('Error: Can not remove a non-temporary entity')
  321. }
  322. repository.destroy(tempEntityId)
  323. repository.destroy(this.CLONE_PREFIX + tempEntityId)
  324. }
  325. }
  326. export default EntityManager