entityManager.ts 14 KB

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