entityManager.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { Query as PiniaOrmQuery, Repository } from 'pinia-orm'
  2. import type { Collection as PiniaOrmCollection } from 'pinia-orm'
  3. import { v4 as uuid4 } from 'uuid'
  4. import * as _ from 'lodash-es'
  5. import { computed } from 'vue'
  6. import ApiRequestService from './apiRequestService'
  7. import UrlUtils from '~/services/utils/urlUtils'
  8. import ApiModel from '~/models/ApiModel'
  9. import ApiResource from '~/models/ApiResource'
  10. import type { AnyJson, AssociativeArray, Collection } from '~/types/data.d'
  11. import models from '~/models/models'
  12. import HydraNormalizer from '~/services/data/normalizer/hydraNormalizer'
  13. import ObjectUtils from '~/services/utils/objectUtils'
  14. import Query from '~/services/data/Query'
  15. /**
  16. * Entity manager: make operations on the models defined with the Pinia-Orm library
  17. *
  18. * TODO: améliorer le typage des méthodes sur le modèle de find()
  19. * @see https://pinia-orm.codedredd.de/
  20. */
  21. class EntityManager {
  22. protected CLONE_PREFIX = '_clone_'
  23. /**
  24. * In instance of ApiRequestService
  25. * @protected
  26. */
  27. protected apiRequestService: ApiRequestService
  28. /**
  29. * A method to retrieve the repository of a given ApiResource
  30. * @protected
  31. */
  32. protected _getRepo: (model: typeof ApiResource) => Repository<ApiResource>
  33. protected _getProfileMask: () => object
  34. public constructor(
  35. apiRequestService: ApiRequestService,
  36. getRepo: (model: typeof ApiResource) => Repository<ApiResource>,
  37. getProfileMask: () => object,
  38. ) {
  39. this.apiRequestService = apiRequestService
  40. this._getRepo = getRepo
  41. this._getProfileMask = getProfileMask
  42. }
  43. /**
  44. * Return the repository for the model
  45. *
  46. * @param model
  47. */
  48. public getRepository(model: typeof ApiResource): Repository<ApiResource> {
  49. return this._getRepo(model)
  50. }
  51. /**
  52. * Return a pinia-orm query for the model
  53. *
  54. * @param model
  55. */
  56. public getQuery(model: typeof ApiResource): PiniaOrmQuery<ApiResource> {
  57. // TODO: quid des uuid?
  58. return this.getRepository(model).where((val) => Number.isInteger(val.id))
  59. }
  60. /**
  61. * Cast an object as an ApiResource
  62. * This in used internally to ensure the object is recognized as an ApiResource
  63. *
  64. * @param model
  65. * @param instance
  66. * @protected
  67. */
  68. // noinspection JSMethodCanBeStatic
  69. protected cast(
  70. model: typeof ApiResource,
  71. instance: ApiResource,
  72. ): ApiResource {
  73. // eslint-disable-next-line new-cap
  74. return new model(instance)
  75. }
  76. /**
  77. * Return the model class with the given entity name
  78. *
  79. * @param entityName
  80. */
  81. public getModelFor(entityName: string): typeof ApiResource {
  82. return models[entityName]
  83. }
  84. /**
  85. * Return the model class from an Opentalent Api IRI
  86. *
  87. * @param iri An IRI of the form .../api/<entity>/...
  88. */
  89. public getModelFromIri(iri: string): typeof ApiResource {
  90. const matches = iri.match(/^\/api\/(\w+)\/.*/)
  91. if (!matches || !matches[1]) {
  92. throw new Error('cannot parse the IRI')
  93. }
  94. return this.getModelFor(matches[1])
  95. }
  96. /**
  97. * Create a new instance of the given model
  98. *
  99. * @param model
  100. * @param properties
  101. */
  102. public newInstance(
  103. model: typeof ApiResource,
  104. properties: object = {},
  105. ): ApiResource {
  106. const repository = this.getRepository(model)
  107. const instance = repository.make(properties)
  108. // Keep track of the model
  109. // TODO : attendre de voir si utile ou non
  110. // instance.setModel(model)
  111. if (
  112. !Object.prototype.hasOwnProperty.call(properties, 'id') ||
  113. // @ts-expect-error Si la première condition passe, on sait que id existe
  114. !properties.id
  115. ) {
  116. // Object has no id yet, we give him a temporary one
  117. instance.id = 'tmp' + uuid4()
  118. }
  119. return this.save(model, instance, true)
  120. }
  121. /**
  122. * Save the model instance into the store
  123. *
  124. * @param model
  125. * @param instance
  126. * @param permanent Is the change already persisted in the datasource? If this is the case, the initial state of this
  127. * record is also updated.
  128. */
  129. public save(
  130. model: typeof ApiResource,
  131. instance: ApiResource,
  132. permanent: boolean = false,
  133. ): ApiResource {
  134. instance = this.cast(model, instance)
  135. if (permanent) {
  136. this.saveInitialState(model, instance)
  137. }
  138. return this.getRepository(model).save(instance)
  139. }
  140. /**
  141. * Find the model instance in the store
  142. * TODO: comment réagit la fonction si l'id n'existe pas dans le store?
  143. *
  144. * @param model
  145. * @param id
  146. */
  147. // @ts-expect-error TODO: corriger au moment de l'implémentation des types génériques
  148. public find<T extends ApiResource>(model: typeof T, id: number | string): T {
  149. const repository = this.getRepository(model)
  150. return repository.find(id) as T
  151. }
  152. /**
  153. * Fetch an ApiModel / ApiResource by its id, save it to the store and returns it
  154. *
  155. * @param model Model of the object to fetch
  156. * @param id Id of the object to fetch
  157. * @param forceRefresh Force a new get request to the api ;
  158. * current object in store will be overwritten if it exists
  159. */
  160. public async fetch(
  161. model: typeof ApiResource,
  162. id: number,
  163. forceRefresh: boolean = false,
  164. ): Promise<ApiResource> {
  165. // If the model instance is already in the store and forceRefresh is false, return the object in store
  166. if (!forceRefresh) {
  167. // TODO: est-ce qu'il y a vraiment des situations où on appellera cette méthode sans le forceRefresh?
  168. const item = this.find(model, id)
  169. if (item && typeof item !== 'undefined') {
  170. return item
  171. }
  172. }
  173. // Else, get the object from the API
  174. const url = UrlUtils.join('api', model.entity, String(id))
  175. const response = await this.apiRequestService.get(url)
  176. // deserialize the response
  177. const attributes = HydraNormalizer.denormalize(response, model)
  178. .data as object
  179. return this.newInstance(model, attributes)
  180. }
  181. /**
  182. * Fetch a collection of model instances
  183. *
  184. * @param model
  185. * @param parent
  186. * @param query
  187. */
  188. public async fetchCollection(
  189. model: typeof ApiResource,
  190. parent: ApiResource | null,
  191. query: Query | null = null,
  192. ): Promise<ComputedRef<Collection>> {
  193. let url
  194. if (parent !== null) {
  195. url = UrlUtils.join('api', parent.entity, '' + parent.id, model.entity)
  196. } else {
  197. url = UrlUtils.join('api', model.entity)
  198. }
  199. if (query) {
  200. url += '?' + query.getUrlQuery()
  201. }
  202. const response = await this.apiRequestService.get(url)
  203. // deserialize the response
  204. const apiCollection = HydraNormalizer.denormalize(response, model)
  205. apiCollection.data.map((attributes: object) => {
  206. return this.newInstance(model, attributes)
  207. })
  208. let piniaOrmQuery = this.getQuery(model)
  209. if (query) {
  210. piniaOrmQuery = query.applyToPiniaOrmQuery(piniaOrmQuery)
  211. }
  212. return computed(() => {
  213. const items: PiniaOrmCollection<ApiResource> = piniaOrmQuery.get()
  214. return {
  215. items,
  216. totalItems: apiCollection.metadata.totalItems,
  217. pagination: {
  218. first: apiCollection.metadata.firstPage || 1,
  219. last: apiCollection.metadata.lastPage || 1,
  220. next: apiCollection.metadata.nextPage || undefined,
  221. previous: apiCollection.metadata.previousPage || undefined,
  222. },
  223. }
  224. })
  225. }
  226. /**
  227. * Persist the model instance as it is in the store into the data source via the API
  228. *
  229. * @param model
  230. * @param instance
  231. */
  232. public async persist(model: typeof ApiModel, instance: ApiModel) {
  233. // Recast in case class definition has been "lost"
  234. // TODO: attendre de voir si cette ligne est nécessaire
  235. instance = this.cast(model, instance)
  236. let url = UrlUtils.join('api', model.entity)
  237. let response
  238. const data: AnyJson = HydraNormalizer.normalizeEntity(instance)
  239. const headers = { profileHash: await this.makeProfileHash() }
  240. if (!instance.isNew()) {
  241. url = UrlUtils.join(url, String(instance.id))
  242. response = await this.apiRequestService.put(url, data, null, headers)
  243. } else {
  244. delete data.id
  245. response = await this.apiRequestService.post(url, data, null, headers)
  246. }
  247. const hydraResponse = HydraNormalizer.denormalize(response, model)
  248. const newInstance = this.newInstance(model, hydraResponse.data)
  249. // Si l'instance était nouvelle avant d'être persistée, elle vient désormais de recevoir un id définitif. On
  250. // peut donc supprimer l'instance temporaire.
  251. if (instance.isNew()) {
  252. this.removeTempAfterPersist(model, instance.id)
  253. }
  254. return newInstance
  255. }
  256. /**
  257. * Send an update request (PUT) to the API with the given data on an existing model instance
  258. *
  259. * @param model
  260. * @param id
  261. * @param data
  262. */
  263. public async patch(
  264. model: typeof ApiModel,
  265. id: number,
  266. data: AssociativeArray,
  267. ) {
  268. const url = UrlUtils.join('api', model.entity, '' + id)
  269. const body = JSON.stringify(data)
  270. const response = await this.apiRequestService.put(url, body)
  271. const hydraResponse = await HydraNormalizer.denormalize(response, model)
  272. return this.newInstance(model, hydraResponse.data)
  273. }
  274. /**
  275. * Delete the model instance from the datasource via the API
  276. *
  277. * @param model
  278. * @param instance
  279. */
  280. public async delete(model: typeof ApiModel, instance: ApiResource) {
  281. const repository = this.getRepository(model)
  282. // If object has been persisted to the datasource, send a delete request
  283. if (!instance.isNew()) {
  284. const url = UrlUtils.join('api', model.entity, String(instance.id))
  285. await this.apiRequestService.delete(url)
  286. }
  287. // reactiveUpdate the store
  288. repository.destroy(instance.id)
  289. }
  290. /**
  291. * Reset the model instance to its initial state (i.e. the state it had when it was fetched from the API)
  292. *
  293. * @param model
  294. * @param instance
  295. */
  296. public reset(model: typeof ApiResource, instance: ApiResource) {
  297. const initialInstance = this.getInitialStateOf(model, instance.id)
  298. if (initialInstance === null) {
  299. throw new Error(
  300. 'no initial state recorded for this object - abort [' +
  301. model.entity +
  302. '/' +
  303. instance.id +
  304. ']',
  305. )
  306. }
  307. const repository = this.getRepository(model)
  308. repository.save(initialInstance)
  309. return initialInstance
  310. }
  311. /**
  312. * Delete all records in the repository of the model
  313. *
  314. * @param model
  315. */
  316. public flush(model: typeof ApiModel) {
  317. const repository = this.getRepository(model)
  318. repository.flush()
  319. }
  320. /**
  321. * Is the model instance a new one, or does it already exist in the data source (=API)
  322. *
  323. * This is a convenient way of testing a model instance you did not already fetch, else prefer the use of the
  324. * isNew() method of ApiResource
  325. *
  326. * @param model
  327. * @param id
  328. */
  329. public isNewInstance(model: typeof ApiModel, id: number | string): boolean {
  330. const repository = this.getRepository(model)
  331. const item = repository.find(id)
  332. if (!item || typeof item === 'undefined') {
  333. // TODO: est-ce qu'il ne faudrait pas lever une erreur ici plutôt?
  334. console.error(model.entity + '/' + id + ' does not exist!')
  335. return false
  336. }
  337. return item.isNew()
  338. }
  339. /**
  340. * Save the state of the model instance in the store, so this state could be restored later
  341. *
  342. * @param model
  343. * @param instance
  344. * @private
  345. */
  346. protected saveInitialState(model: typeof ApiResource, instance: ApiResource) {
  347. const repository = this.getRepository(model)
  348. // Clone and prefix id
  349. const clone = _.cloneDeep(instance)
  350. clone.id = this.CLONE_PREFIX + clone.id
  351. repository.save(clone)
  352. }
  353. /**
  354. * Return the saved state of the model instance from the store
  355. *
  356. * @param model
  357. * @param id
  358. * @private
  359. */
  360. protected getInitialStateOf(
  361. model: typeof ApiResource,
  362. id: string | number,
  363. ): ApiResource | null {
  364. const repository = this.getRepository(model)
  365. // Find the clone by id
  366. const instance = repository.find(this.CLONE_PREFIX + id)
  367. if (instance === null) {
  368. return null
  369. }
  370. // Restore the initial id
  371. instance.id = id
  372. return instance
  373. }
  374. /**
  375. * Delete the temporary model instance from the repo after it was persisted via the api, replaced by the instance
  376. * that has been returned by the api with is definitive id.
  377. *
  378. * @param model
  379. * @param tempInstanceId
  380. * @private
  381. */
  382. protected removeTempAfterPersist(
  383. model: typeof ApiResource,
  384. tempInstanceId: number | string,
  385. ) {
  386. const repository = this.getRepository(model)
  387. const instance = repository.find(tempInstanceId)
  388. if (!instance || typeof instance === 'undefined') {
  389. // TODO: il vaudrait peut-être mieux lever une erreur ici?
  390. console.error(model.entity + '/' + tempInstanceId + ' does not exist!')
  391. return
  392. }
  393. if (!instance.isNew()) {
  394. throw new Error('Error: Can not remove a non-temporary model instance')
  395. }
  396. repository.destroy(tempInstanceId)
  397. repository.destroy(this.CLONE_PREFIX + tempInstanceId)
  398. }
  399. protected async makeProfileHash(): Promise<string> {
  400. const mask = this._getProfileMask()
  401. return await ObjectUtils.hash(mask)
  402. }
  403. }
  404. export default EntityManager