entityManager.ts 13 KB

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