entityManager.ts 14 KB

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