entityManager.ts 14 KB

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