entityManager.ts 13 KB

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