entityManager.ts 13 KB

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