entityManager.ts 14 KB

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