entityManager.ts 14 KB

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