entityManager.ts 11 KB

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