entityManager.ts 14 KB

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