entityManager.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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+)\/.*/)
  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>(model: T, id: number | string): T {
  164. const repository = this.getRepository(model)
  165. return repository.find(id) as T
  166. }
  167. /**
  168. * Fetch an ApiModel / ApiResource by its id, save it to the store and returns it
  169. *
  170. * @param model Model of the object to fetch
  171. * @param id Id of the object to fetch
  172. */
  173. public async fetch<T extends typeof ApiResource>(
  174. model: T,
  175. id?: number | null,
  176. ): Promise<InstanceType<T>> {
  177. // Else, get the object from the API
  178. const url = UrlUtils.join('api', model.entity, id ? String(id) : '')
  179. const response = await this.apiRequestService.get(url)
  180. // deserialize the response
  181. // @ts-expect-error Response here is a Json Hydra response
  182. const attributes = HydraNormalizer.denormalize(response, model)
  183. .data as object
  184. return this.newInstance(model, attributes)
  185. }
  186. /**
  187. * Fetch a collection of model instances
  188. *
  189. * @param model
  190. * @param parent
  191. * @param query
  192. */
  193. public async fetchCollection<T extends typeof ApiResource>(
  194. model: T,
  195. parent: InstanceType<T> | null,
  196. query: Query | null = null,
  197. ): Promise<ComputedRef<Collection<InstanceType<T>>>> {
  198. let url
  199. if (parent !== null) {
  200. url = UrlUtils.join(
  201. 'api',
  202. parent.$entity(),
  203. '' + String(parent.id),
  204. model.entity,
  205. )
  206. } else {
  207. url = UrlUtils.join('api', model.entity)
  208. }
  209. if (query) {
  210. url += '?' + query.getUrlQuery()
  211. }
  212. const response = await this.apiRequestService.get(url)
  213. // deserialize the response
  214. // @ts-expect-error Response here is a Json Hydra response
  215. const apiCollection = HydraNormalizer.denormalize(
  216. response,
  217. model,
  218. ) as ApiCollection
  219. apiCollection.data.map((attributes: object) => {
  220. return this.newInstance(model, attributes)
  221. })
  222. let piniaOrmQuery = this.getQuery(model)
  223. if (query) {
  224. piniaOrmQuery = query.applyToPiniaOrmQuery(piniaOrmQuery)
  225. }
  226. const res = computed(() => {
  227. const items: PiniaOrmCollection<InstanceType<T>> = piniaOrmQuery.get()
  228. return {
  229. items,
  230. totalItems: apiCollection.metadata.totalItems,
  231. pagination: {
  232. first: apiCollection.metadata.first || 1,
  233. last: apiCollection.metadata.last || 1,
  234. next: apiCollection.metadata.next || undefined,
  235. previous: apiCollection.metadata.previous || undefined,
  236. },
  237. }
  238. })
  239. // @ts-expect-error Needed to avoid 'Cannot stringify non POJO' occasional bugs
  240. res.toJSON = () => {
  241. return 'Computed result from fetchCollection at : ' + url
  242. }
  243. return res
  244. }
  245. /**
  246. * Persist the model instance as it is in the store into the data source via the API
  247. *
  248. * @param instance
  249. */
  250. public async persist<T extends ApiResource>(instance: T): Promise<T> {
  251. const model = this.getModel(instance)
  252. let url = UrlUtils.join('api', model.entity)
  253. let response
  254. this.validateEntity(instance)
  255. const data: AnyJson = HydraNormalizer.normalizeEntity(instance)
  256. const headers = { profileHash: await this.makeProfileHash() }
  257. if (!instance.isNew()) {
  258. if (!model.isIdLess()) {
  259. url = UrlUtils.join(url, String(instance.id))
  260. }
  261. response = await this.apiRequestService.patch(url, data, null, headers)
  262. } else {
  263. delete data.id
  264. response = await this.apiRequestService.post(url, data, null, headers)
  265. }
  266. const hydraResponse = HydraNormalizer.denormalize(response, model)
  267. const newInstance = this.newInstance(model, hydraResponse.data)
  268. // Si l'instance était nouvelle avant d'être persistée, elle vient désormais de recevoir un id définitif. On
  269. // peut donc supprimer l'instance temporaire.
  270. if (instance.isNew()) {
  271. this.removeTempAfterPersist(model, instance.id)
  272. }
  273. return newInstance as T
  274. }
  275. /**
  276. * Send an update request (PATCH) to the API with the given data on an existing model instance
  277. *
  278. * @param model
  279. * @param id
  280. * @param data
  281. */
  282. public async patch(
  283. model: typeof ApiModel,
  284. id: number,
  285. data: AssociativeArray,
  286. ) {
  287. const url = UrlUtils.join('api', model.entity, '' + id)
  288. const body = JSON.stringify(data)
  289. const response = await this.apiRequestService.patch(url, body)
  290. // @ts-expect-error Response here is a Json Hydra response
  291. const hydraResponse = HydraNormalizer.denormalize(response, model)
  292. return this.newInstance(model, hydraResponse.data)
  293. }
  294. /**
  295. * Delete the model instance from the datasource via the API
  296. *
  297. * @param instance
  298. * @param instance
  299. */
  300. public async delete<T extends ApiResource>(instance: T) {
  301. const model = this.getModel(instance)
  302. instance = this.cast(model, instance) as T
  303. console.log('delete', instance)
  304. this.validateEntity(instance)
  305. const repository = this.getRepository(model)
  306. this.validateEntity(instance)
  307. // If object has been persisted to the datasource, send a delete request
  308. if (!instance.isNew()) {
  309. const url = UrlUtils.join('api', model.entity, String(instance.id))
  310. await this.apiRequestService.delete(url)
  311. }
  312. // reactiveUpdate the store
  313. repository.destroy(instance.id)
  314. }
  315. /**
  316. * Reset the model instance to its initial state (i.e. the state it had when it was fetched from the API)
  317. *
  318. * @param model
  319. * @param instance
  320. */
  321. public reset<T extends ApiResource>(instance: T) {
  322. const model = this.getModel(instance)
  323. const initialInstance = this.getInitialStateOf(model, instance.id)
  324. if (initialInstance === null) {
  325. throw new Error(
  326. 'no initial state recorded for this object - abort [' +
  327. model.entity +
  328. '/' +
  329. instance.id +
  330. ']',
  331. )
  332. }
  333. const repository = this.getRepository(model)
  334. repository.save(initialInstance)
  335. return initialInstance
  336. }
  337. /**
  338. * Delete all records in the repository of the model
  339. *
  340. * @param model
  341. */
  342. public flush<T extends typeof ApiResource>(model: T) {
  343. const repository = this.getRepository(model)
  344. repository.flush()
  345. }
  346. /**
  347. * Is the model instance a new one, or does it already exist in the data source (=API)
  348. *
  349. * This is a convenient way of testing a model instance you did not already fetch, else prefer the use of the
  350. * isNew() method of ApiResource
  351. *
  352. * @param model
  353. * @param id
  354. */
  355. public isNewInstance<T extends typeof ApiResource>(
  356. model: T,
  357. id: number | string,
  358. ): boolean {
  359. const repository = this.getRepository(model)
  360. const item = repository.find(id)
  361. if (!item || typeof item === 'undefined') {
  362. // TODO: est-ce qu'il ne faudrait pas lever une erreur ici plutôt?
  363. console.error(model.entity + '/' + id + ' does not exist!')
  364. return false
  365. }
  366. return item.isNew()
  367. }
  368. /**
  369. * Save the state of the model instance in the store, so this state could be restored later
  370. *
  371. * @param model
  372. * @param instance
  373. * @private
  374. */
  375. protected saveInitialState<T extends typeof ApiResource>(
  376. model: T,
  377. instance: InstanceType<T>,
  378. ) {
  379. const repository = this.getRepository(model)
  380. // Clone and prefix id
  381. const clone = _.cloneDeep(instance)
  382. clone.id = this.CLONE_PREFIX + clone.id
  383. repository.save(clone)
  384. }
  385. /**
  386. * Return the saved state of the model instance from the store
  387. *
  388. * @param model
  389. * @param id
  390. * @private
  391. */
  392. protected getInitialStateOf<T extends typeof ApiResource>(
  393. model: T,
  394. id: string | number,
  395. ): InstanceType<T> | null {
  396. const repository = this.getRepository(model)
  397. // Find the clone by id
  398. const instance = repository.find(this.CLONE_PREFIX + id)
  399. if (instance === null) {
  400. return null
  401. }
  402. // Restore the initial id
  403. instance.id = id
  404. return instance
  405. }
  406. /**
  407. * Delete the temporary model instance from the repo after it was persisted via the api, replaced by the instance
  408. * that has been returned by the api with is definitive id.
  409. *
  410. * @param model
  411. * @param tempInstanceId
  412. * @private
  413. */
  414. protected removeTempAfterPersist<T extends typeof ApiResource>(
  415. model: T,
  416. tempInstanceId: number | string,
  417. ) {
  418. const repository = this.getRepository(model)
  419. const instance = repository.find(tempInstanceId)
  420. if (!instance || typeof instance === 'undefined') {
  421. // TODO: il vaudrait peut-être mieux lever une erreur ici?
  422. console.error(model.entity + '/' + tempInstanceId + ' does not exist!')
  423. return
  424. }
  425. if (!instance.isNew()) {
  426. throw new Error('Error: Can not remove a non-temporary model instance')
  427. }
  428. repository.destroy(tempInstanceId)
  429. repository.destroy(this.CLONE_PREFIX + tempInstanceId)
  430. }
  431. protected async makeProfileHash(): Promise<string> {
  432. const mask = this._getProfileMask()
  433. return await ObjectUtils.hash(mask)
  434. }
  435. /**
  436. * Validate the entity, and throw an error if it's not correctly defined.
  437. * @param instance
  438. * @protected
  439. */
  440. protected validateEntity(instance: unknown): void {
  441. if (Object.prototype.hasOwnProperty.call(instance, 'id')) {
  442. // @ts-expect-error At this point, we're sure there is an id property
  443. const id = instance.id
  444. if (
  445. !(typeof id === 'number') &&
  446. !(typeof id === 'string' && id.startsWith('tmp'))
  447. ) {
  448. // The id is a pinia orm Uid, the entity has been created using the `new` keyword (not supported for now)
  449. throw new Error(
  450. 'Definition error for the entity, did you use the entityManager.newInstance(...) method?\n' +
  451. JSON.stringify(instance),
  452. )
  453. }
  454. }
  455. }
  456. }
  457. export default EntityManager