entityManager.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 {useProfileAccessStore} from "~/store/profile/access";
  8. import ApiResource from "~/models/ApiResource";
  9. import {MyProfile} from "~/models/Access/MyProfile";
  10. import { v4 as uuid4 } from 'uuid';
  11. import {AssociativeArray, Collection} from "~/types/data.d";
  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(apiRequestService: ApiRequestService) {
  21. this.apiRequestService = apiRequestService
  22. }
  23. /**
  24. * Return the repository for the model
  25. *
  26. * @param model
  27. */
  28. public getRepository(model: typeof ApiResource): Repository<ApiResource> {
  29. return useRepo(model)
  30. }
  31. /**
  32. * Create a new instance of the given model
  33. *
  34. * @param model
  35. * @param properties
  36. */
  37. public new(model: typeof ApiResource, properties: object = {}) {
  38. const repository = this.getRepository(model)
  39. const entity = repository.make(properties)
  40. // @ts-ignore
  41. if (!properties.hasOwnProperty('id') || !properties.id) {
  42. // Object has no id yet, we give him a temporary one
  43. entity.id = 'tmp' + uuid4()
  44. }
  45. repository.save(entity)
  46. this.saveInitialState(model, entity)
  47. return entity
  48. }
  49. /**
  50. * On met à jour directement l'entité par référence ou la liste d'entités,
  51. * pour maintenir la réactivité lorsque l'entité ou l'array est déclarée comme réactive
  52. *
  53. * Attention à ce que le sujet et la nouvelle valeur soient des objets de même type
  54. *
  55. * @see http://underscorejs.org/#extend
  56. * @param subject
  57. * @param newValue
  58. */
  59. public reactiveUpdate(subject: ApiResource | Array<ApiResource>, newValue: ApiResource | Array<ApiResource>) {
  60. if (typeof subject !== typeof newValue) { // TODO: remplacer par des règles typescript
  61. console.log('Error : subject and new value have to share the same type')
  62. return
  63. }
  64. if (Array.isArray(subject)) {
  65. this.reactiveUpdateArray(subject as Array<ApiResource>, newValue as Array<ApiResource>)
  66. } else {
  67. this.reactiveUpdateItem(subject as ApiResource, newValue as ApiResource)
  68. }
  69. }
  70. private reactiveUpdateItem(entity: ApiResource, newEntity: ApiResource) {
  71. useExtend(entity, newEntity)
  72. }
  73. private reactiveUpdateArray(items: Array<ApiResource>, newItems: Array<ApiResource>) {
  74. items.length = 0
  75. newItems.forEach((f: ApiResource) => {
  76. items.push(f)
  77. })
  78. }
  79. /**
  80. * Fetch an Entity / ApiResource by its id, save it to the store and returns it
  81. *
  82. * @param model Model of the object to fetch
  83. * @param id Id of the object to fetch
  84. * @param forceRefresh Force a new get request to the api ;
  85. * current object in store will be overwritten if it exists
  86. */
  87. public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
  88. const repository = this.getRepository(model)
  89. // If the entity is already in the store and forceRefresh is false, return the object in store
  90. if (!forceRefresh) {
  91. const item = repository.find(id)
  92. if (item && typeof item !== 'undefined') {
  93. return item
  94. }
  95. }
  96. // Else, get the object from the API
  97. const url = Url.join('api', model.entity, String(id))
  98. const response = await this.apiRequestService.get(url)
  99. // deserialize the response
  100. const attributes = HydraDenormalizer.denormalize(response).data as object
  101. return this.new(model, attributes)
  102. }
  103. public findBy(model: typeof ApiResource, query: AssociativeArray) {
  104. // TODO: implement
  105. }
  106. public async fetchAll(model: typeof ApiResource, page: number = 1): Promise<Collection> {
  107. let url = Url.join('api', model.entity)
  108. if (page !== 1) {
  109. url = Url.join(url, '?page=' + page)
  110. }
  111. console.log(url)
  112. const response = await this.apiRequestService.get(url)
  113. // deserialize the response
  114. const collection = HydraDenormalizer.denormalize(response)
  115. const items = collection.data.map((attributes: object) => {
  116. return this.new(model, attributes)
  117. })
  118. return {
  119. items,
  120. totalItems: collection.metadata.totalItems,
  121. firstPage: collection.metadata.firstPage,
  122. lastPage: collection.metadata.lastPage,
  123. nextPage: collection.metadata.nextPage,
  124. previousPage: collection.metadata.previousPage,
  125. }
  126. }
  127. /**
  128. * Persist the entity as it is in the store into the data source via the API
  129. *
  130. * @param model
  131. * @param entity
  132. */
  133. public async persist(model: typeof ApiModel, entity: ApiModel) {
  134. const repository = this.getRepository(model)
  135. let url = Url.join('api', model.entity)
  136. let response
  137. const data = ModelNormalizer.normalize(entity)
  138. if (!entity.isNew()) {
  139. url = Url.join(url, String(entity.id))
  140. response = await this.apiRequestService.put(url, data)
  141. } else {
  142. delete data.id
  143. response = await this.apiRequestService.post(url, data)
  144. }
  145. const hydraResponse = await HydraDenormalizer.denormalize(response)
  146. const returnedEntity = this.new(model, hydraResponse.data)
  147. this.saveInitialState(model, returnedEntity)
  148. // Save data into the store
  149. repository.save(returnedEntity)
  150. if (['accesses', 'organizations', 'parameters', 'subdomains'].includes(model.entity)) {
  151. await this.refreshProfile()
  152. }
  153. this.reactiveUpdate(entity, returnedEntity)
  154. }
  155. /**
  156. * Delete the entity from the datasource via the API
  157. *
  158. * @param model
  159. * @param entity
  160. */
  161. public async delete(model: typeof ApiModel, entity: ApiResource) {
  162. const repository = this.getRepository(model)
  163. // If object has been persisted to the datasource, send a delete request
  164. if (!entity.isNew()) {
  165. const url = Url.join('api', model.entity, String(entity.id))
  166. await this.apiRequestService.delete(url)
  167. }
  168. // reactiveUpdate the store
  169. repository.destroy(entity.id)
  170. }
  171. /**
  172. * Reset the entity to its initial state (i.e. the state it had when it was fetched from the API)
  173. *
  174. * @param model
  175. * @param entity
  176. */
  177. public reset(model: typeof ApiResource, entity: ApiResource) {
  178. const initialEntity = this.getInitialStateOf(model, entity.id)
  179. if (initialEntity === null) {
  180. throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + entity.id + ']')
  181. }
  182. const repository = this.getRepository(model)
  183. repository.save(initialEntity)
  184. this.reactiveUpdate(entity, initialEntity)
  185. }
  186. /**
  187. * Re-fetch the user profile and reactiveUpdate the store
  188. */
  189. public async refreshProfile() {
  190. const response = await this.apiRequestService.get('api/my_profile')
  191. // deserialize the response
  192. const hydraResponse = await HydraDenormalizer.denormalize(response)
  193. const profile = this.new(MyProfile, hydraResponse.data)
  194. const profileAccessStore = useProfileAccessStore()
  195. profileAccessStore.setProfile(profile)
  196. }
  197. /**
  198. * Delete all records in the repository of the model
  199. *
  200. * @param model
  201. */
  202. public async flush(model: typeof ApiModel) {
  203. const repository = this.getRepository(model)
  204. repository.flush()
  205. }
  206. /**
  207. * Is the entity a new one, or does it already exist in the data source (=API)
  208. *
  209. * @param model
  210. * @param id
  211. */
  212. public isNewEntity(model: typeof ApiModel, id: number | string): boolean {
  213. const repository = this.getRepository(model)
  214. const item = repository.find(id)
  215. if (!item || typeof item === 'undefined') {
  216. console.error(model.entity + '/' + id, ' does not exist!')
  217. return false
  218. }
  219. return item.isNew()
  220. }
  221. /**
  222. * Save the state of the entity in the store, so this state could be be restored later
  223. *
  224. * @param model
  225. * @param entity
  226. * @private
  227. */
  228. private saveInitialState(model: typeof ApiResource, entity: ApiResource) {
  229. const repository = this.getRepository(model)
  230. // Clone and prefix id
  231. const clone = useCloneDeep(entity)
  232. clone.id = this.CLONE_PREFIX + clone.id
  233. repository.save(clone)
  234. }
  235. /**
  236. * Return the saved state of the entity from the store
  237. *
  238. * @param model
  239. * @param id
  240. * @private
  241. */
  242. private getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
  243. const repository = this.getRepository(model)
  244. // Find the clone by id
  245. const entity = repository.find(this.CLONE_PREFIX + id)
  246. if (entity === null) {
  247. return null
  248. }
  249. // Restore the initial id
  250. entity.id = id
  251. return entity
  252. }
  253. }
  254. export default EntityManager