entityManager.ts 12 KB

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