entityManager.ts 12 KB

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