entityManager.ts 12 KB

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