entityManager.ts 12 KB

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