entityManager.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 (permanent) {
  108. this.saveInitialState(model, instance)
  109. }
  110. return this.getRepository(model).save(instance)
  111. }
  112. /**
  113. * Find the model instance in the store
  114. * TODO: comment réagit la fonction si l'id n'existe pas dans le store?
  115. *
  116. * @param model
  117. * @param id
  118. */
  119. // @ts-ignore
  120. public find<T extends ApiResource>(model: typeof T, id: number): T {
  121. const repository = this.getRepository(model)
  122. return repository.find(id) as T
  123. }
  124. /**
  125. * Fetch an ApiModel / ApiResource by its id, save it to the store and returns it
  126. *
  127. * @param model Model of the object to fetch
  128. * @param id Id of the object to fetch
  129. * @param forceRefresh Force a new get request to the api ;
  130. * current object in store will be overwritten if it exists
  131. */
  132. public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
  133. // If the model instance is already in the store and forceRefresh is false, return the object in store
  134. if (!forceRefresh) {
  135. const item = this.find(model, id)
  136. if (item && typeof item !== 'undefined') {
  137. return item
  138. }
  139. }
  140. // Else, get the object from the API
  141. const url = UrlUtils.join('api', model.entity, String(id))
  142. const response = await this.apiRequestService.get(url)
  143. // deserialize the response
  144. const attributes = HydraDenormalizer.denormalize(response).data as object
  145. return this.newInstance(model, attributes)
  146. }
  147. /**
  148. * Fetch a collection of model instances
  149. * The content of `query` is converted into a query-string in the request URL
  150. *
  151. * @param model
  152. * @param query
  153. * @param parent
  154. */
  155. public async fetchCollection(model: typeof ApiResource, parent: ApiResource | null, query: AssociativeArray = []): Promise<Collection> {
  156. let url
  157. if (parent !== null) {
  158. url = UrlUtils.join('api', parent.entity, '' + parent.id, model.entity)
  159. } else {
  160. url = UrlUtils.join('api', model.entity)
  161. }
  162. const response = await this.apiRequestService.get(url, query)
  163. // deserialize the response
  164. const apiCollection = HydraDenormalizer.denormalize(response)
  165. const items = apiCollection.data.map((attributes: object) => {
  166. return this.newInstance(model, attributes)
  167. })
  168. return {
  169. items,
  170. totalItems: apiCollection.metadata.totalItems,
  171. pagination: {
  172. first: apiCollection.metadata.firstPage || 1,
  173. last: apiCollection.metadata.lastPage || 1,
  174. next: apiCollection.metadata.nextPage || undefined,
  175. previous: apiCollection.metadata.previousPage || undefined,
  176. }
  177. }
  178. }
  179. /**
  180. * Persist the model instance as it is in the store into the data source via the API
  181. *
  182. * @param model
  183. * @param instance
  184. */
  185. public async persist(model: typeof ApiModel, instance: ApiModel) {
  186. // Recast in case class definition has been "lost"
  187. // TODO: attendre de voir si cette ligne est nécessaire
  188. // instance = this.cast(model, instance)
  189. let url = UrlUtils.join('api', model.entity)
  190. let response
  191. const data: any = instance.$toJson()
  192. if (!instance.isNew()) {
  193. url = UrlUtils.join(url, String(instance.id))
  194. response = await this.apiRequestService.put(url, data)
  195. } else {
  196. delete data.id
  197. response = await this.apiRequestService.post(url, data)
  198. }
  199. const hydraResponse = await HydraDenormalizer.denormalize(response)
  200. const newInstance = this.newInstance(model, hydraResponse.data)
  201. // Si l'instance était nouvelle avant d'être persistée, elle vient désormais de recevoir un id définitif. On
  202. // peut donc supprimer l'instance temporaire.
  203. if (instance.isNew()) {
  204. this.removeTempAfterPersist(model, instance.id)
  205. }
  206. return newInstance
  207. }
  208. /**
  209. * Send an update request (PUT) to the API with the given data on an existing model instance
  210. *
  211. * @param model
  212. * @param id
  213. * @param data
  214. */
  215. public async patch(model: typeof ApiModel, id: number, data: AssociativeArray) {
  216. let url = UrlUtils.join('api', model.entity, ''+id)
  217. const body = JSON.stringify(data)
  218. const response = await this.apiRequestService.put(url, body)
  219. const hydraResponse = await HydraDenormalizer.denormalize(response)
  220. return this.newInstance(model, hydraResponse.data)
  221. }
  222. /**
  223. * Delete the model instance from the datasource via the API
  224. *
  225. * @param model
  226. * @param instance
  227. */
  228. public async delete(model: typeof ApiModel, instance: ApiResource) {
  229. const repository = this.getRepository(model)
  230. // If object has been persisted to the datasource, send a delete request
  231. if (!instance.isNew()) {
  232. const url = UrlUtils.join('api', model.entity, String(instance.id))
  233. await this.apiRequestService.delete(url)
  234. }
  235. // reactiveUpdate the store
  236. repository.destroy(instance.id)
  237. }
  238. /**
  239. * Reset the model instance to its initial state (i.e. the state it had when it was fetched from the API)
  240. *
  241. * @param model
  242. * @param instance
  243. */
  244. public reset(model: typeof ApiResource, instance: ApiResource) {
  245. const initialInstance = this.getInitialStateOf(model, instance.id)
  246. if (initialInstance === null) {
  247. throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + instance.id + ']')
  248. }
  249. const repository = this.getRepository(model)
  250. repository.save(initialInstance)
  251. return initialInstance
  252. }
  253. /**
  254. * @todo: à déplacer dans le store directement
  255. * @Deprecated : a priori ce n'est pas le bon service pour mettre à jour le profil, on devrait voir ça
  256. * depuis un service dédié, un composable, ou directement dans le store ==> oui !
  257. *
  258. * Re-fetch the user profile and update the store
  259. */
  260. public async refreshProfile(accessId: number | null = null) {
  261. const accessProfileStore = useAccessProfileStore()
  262. if (accessId === null) {
  263. accessId = accessProfileStore.currentAccessId
  264. }
  265. // Sans le flush, on observe un bug non-expliqué au rechargement de la page en mode dev : la fonction save
  266. // du repo de MyProfile ne fonctionne pas quand le plugin init.server.ts re-fetch le profil
  267. this.flush(MyProfile)
  268. const profile = await this.fetch(MyProfile, accessId, true)
  269. // On met à jour le store accessProfile
  270. accessProfileStore.setProfile(profile)
  271. }
  272. /**
  273. * Delete all records in the repository of the model
  274. *
  275. * @param model
  276. */
  277. public flush(model: typeof ApiModel) {
  278. const repository = this.getRepository(model)
  279. repository.flush()
  280. }
  281. /**
  282. * Is the model instance a new one, or does it already exist in the data source (=API)
  283. *
  284. * This is a convenient way of testing a model instance you did not already fetch, else prefer the use of the
  285. * isNew() method of ApiResource
  286. *
  287. * @param model
  288. * @param id
  289. */
  290. public isNewInstance(model: typeof ApiModel, id: number | string): boolean {
  291. const repository = this.getRepository(model)
  292. const item = repository.find(id)
  293. if (!item || typeof item === 'undefined') {
  294. // TODO: est-ce qu'il ne faudrait pas lever une erreur ici plutôt?
  295. console.error(model.entity + '/' + id + ' does not exist!')
  296. return false
  297. }
  298. return item.isNew()
  299. }
  300. /**
  301. * Save the state of the model instance in the store, so this state could be restored later
  302. *
  303. * @param model
  304. * @param instance
  305. * @private
  306. */
  307. protected saveInitialState(model: typeof ApiResource, instance: ApiResource) {
  308. const repository = this.getRepository(model)
  309. // Clone and prefix id
  310. const clone = _.cloneDeep(instance)
  311. clone.id = this.CLONE_PREFIX + clone.id
  312. repository.save(clone)
  313. }
  314. /**
  315. * Return the saved state of the model instance from the store
  316. *
  317. * @param model
  318. * @param id
  319. * @private
  320. */
  321. protected getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
  322. const repository = this.getRepository(model)
  323. // Find the clone by id
  324. const instance = repository.find(this.CLONE_PREFIX + id)
  325. if (instance === null) {
  326. return null
  327. }
  328. // Restore the initial id
  329. instance.id = id
  330. return instance
  331. }
  332. /**
  333. * Delete the temporary model instance from the repo after it was persisted via the api, replaced by the instance
  334. * that has been returned by the api with is definitive id.
  335. *
  336. * @param model
  337. * @param tempInstanceId
  338. * @private
  339. */
  340. protected removeTempAfterPersist(model: typeof ApiResource, tempInstanceId: number | string) {
  341. const repository = this.getRepository(model)
  342. const instance = repository.find(tempInstanceId)
  343. if (!instance || typeof instance === 'undefined') {
  344. // TODO: il vaudrait peut-être mieux lever une erreur ici?
  345. console.error(model.entity + '/' + tempInstanceId + ' does not exist!')
  346. return
  347. }
  348. if (!instance.isNew()) {
  349. throw new Error('Error: Can not remove a non-temporary model instance')
  350. }
  351. repository.destroy(tempInstanceId)
  352. repository.destroy(this.CLONE_PREFIX + tempInstanceId)
  353. }
  354. }
  355. export default EntityManager