entityManager.ts 12 KB

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