entityManager.ts 13 KB

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