entityManager.ts 13 KB

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