entityManager.ts 12 KB

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