entityManager.ts 13 KB

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