entityManager.ts 14 KB

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