entityManager.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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(
  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. public cast(model: typeof ApiResource, entity: ApiResource): ApiResource {
  35. return new model(entity)
  36. }
  37. /**
  38. * Create a new instance of the given model
  39. *
  40. * @param model
  41. * @param properties
  42. */
  43. public newInstance(model: typeof ApiResource, properties: object = {}): ApiResource {
  44. const repository = this.getRepository(model)
  45. let entity = repository.make(properties)
  46. // @ts-ignore
  47. if (!properties.hasOwnProperty('id') || !properties.id) {
  48. // Object has no id yet, we give him a temporary one
  49. entity.id = 'tmp' + uuid4()
  50. }
  51. entity = repository.save(entity)
  52. this.saveInitialState(model, entity)
  53. return entity
  54. }
  55. /**
  56. * Save the entity into the store
  57. *
  58. * @param model
  59. * @param entity
  60. */
  61. public save(model: typeof ApiResource, entity: ApiResource): ApiResource {
  62. return this.getRepository(model).save(entity)
  63. }
  64. /**
  65. * Find the entity into the store
  66. *
  67. * @param model
  68. * @param id
  69. */
  70. // @ts-ignore
  71. public find<T extends ApiResource>(model: typeof T, id: number): T {
  72. const repository = this.getRepository(model)
  73. return repository.find(id) as T
  74. }
  75. /**
  76. * Fetch an Entity / ApiResource by its id, save it to the store and returns it
  77. *
  78. * @param model Model of the object to fetch
  79. * @param id Id of the object to fetch
  80. * @param forceRefresh Force a new get request to the api ;
  81. * current object in store will be overwritten if it exists
  82. */
  83. public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
  84. const repository = this.getRepository(model)
  85. // If the entity is already in the store and forceRefresh is false, return the object in store
  86. if (!forceRefresh) {
  87. const item = repository.find(id)
  88. if (item && typeof item !== 'undefined') {
  89. return item
  90. }
  91. }
  92. // Else, get the object from the API
  93. const url = Url.join('api', model.entity, String(id))
  94. const response = await this.apiRequestService.get(url)
  95. // deserialize the response
  96. const attributes = HydraDenormalizer.denormalize(response).data as object
  97. return this.newInstance(model, attributes)
  98. }
  99. public async fetchBy(model: typeof ApiResource, query: AssociativeArray, page: number = 1): Promise<Collection> {
  100. let url = Url.join('api', model.entity)
  101. if (page !== 1) {
  102. query['page'] = page
  103. }
  104. const response = await this.apiRequestService.get(url, query)
  105. // deserialize the response
  106. const apiCollection = HydraDenormalizer.denormalize(response)
  107. const items = apiCollection.data.map((attributes: object) => {
  108. return this.newInstance(model, attributes)
  109. })
  110. return {
  111. items,
  112. totalItems: apiCollection.metadata.totalItems,
  113. pagination: {
  114. first: apiCollection.metadata.firstPage || 1,
  115. last: apiCollection.metadata.lastPage || 1,
  116. next: apiCollection.metadata.nextPage || undefined,
  117. previous: apiCollection.metadata.previousPage || undefined,
  118. }
  119. }
  120. }
  121. public async fetchAll(model: typeof ApiResource, page: number = 1): Promise<Collection> {
  122. return this.fetchBy(model, [], page)
  123. }
  124. /**
  125. * Persist the entity as it is in the store into the data source via the API
  126. *
  127. * @param model
  128. * @param entity
  129. */
  130. public async persist(model: typeof ApiModel, entity: ApiModel) {
  131. const repository = this.getRepository(model)
  132. // Recast in case class definition has been "lost"
  133. entity = this.cast(model, entity)
  134. let url = Url.join('api', model.entity)
  135. let response
  136. const data = ModelNormalizer.normalize(entity)
  137. if (!entity.isNew()) {
  138. url = Url.join(url, String(entity.id))
  139. response = await this.apiRequestService.put(url, data)
  140. } else {
  141. delete data.id
  142. response = await this.apiRequestService.post(url, data)
  143. }
  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. if (['accesses', 'organizations', 'parameters', 'subdomains'].includes(model.entity)) {
  150. await this.refreshProfile()
  151. }
  152. return returnedEntity
  153. }
  154. /**
  155. * Delete the entity from the datasource via the API
  156. *
  157. * @param model
  158. * @param entity
  159. */
  160. public async delete(model: typeof ApiModel, entity: ApiResource) {
  161. const repository = this.getRepository(model)
  162. // If object has been persisted to the datasource, send a delete request
  163. if (!entity.isNew()) {
  164. const url = Url.join('api', model.entity, String(entity.id))
  165. await this.apiRequestService.delete(url)
  166. }
  167. // reactiveUpdate the store
  168. repository.destroy(entity.id)
  169. }
  170. /**
  171. * Reset the entity to its initial state (i.e. the state it had when it was fetched from the API)
  172. *
  173. * @param model
  174. * @param entity
  175. */
  176. public reset(model: typeof ApiResource, entity: ApiResource) {
  177. const initialEntity = this.getInitialStateOf(model, entity.id)
  178. if (initialEntity === null) {
  179. throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + entity.id + ']')
  180. }
  181. const repository = this.getRepository(model)
  182. repository.save(initialEntity)
  183. return initialEntity
  184. }
  185. /**
  186. * Re-fetch the user profile and reactiveUpdate the store
  187. */
  188. public async refreshProfile() {
  189. const response = await this.apiRequestService.get('api/my_profile')
  190. // deserialize the response
  191. const hydraResponse = await HydraDenormalizer.denormalize(response)
  192. const profile = this.newInstance(MyProfile, hydraResponse.data)
  193. const profileAccessStore = useProfileAccessStore()
  194. profileAccessStore.setProfile(profile)
  195. }
  196. /**
  197. * Delete all records in the repository of the model
  198. *
  199. * @param model
  200. */
  201. public async flush(model: typeof ApiModel) {
  202. const repository = this.getRepository(model)
  203. repository.flush()
  204. }
  205. /**
  206. * Is the entity a new one, or does it already exist in the data source (=API)
  207. *
  208. * @param model
  209. * @param id
  210. */
  211. public isNewEntity(model: typeof ApiModel, id: number | string): boolean {
  212. const repository = this.getRepository(model)
  213. const item = repository.find(id)
  214. if (!item || typeof item === 'undefined') {
  215. console.error(model.entity + '/' + id, ' does not exist!')
  216. return false
  217. }
  218. return item.isNew()
  219. }
  220. /**
  221. * Save the state of the entity in the store, so this state could be be restored later
  222. *
  223. * @param model
  224. * @param entity
  225. * @private
  226. */
  227. private saveInitialState(model: typeof ApiResource, entity: ApiResource) {
  228. const repository = this.getRepository(model)
  229. // Clone and prefix id
  230. const clone = useCloneDeep(entity)
  231. clone.id = this.CLONE_PREFIX + clone.id
  232. repository.save(clone)
  233. }
  234. /**
  235. * Return the saved state of the entity from the store
  236. *
  237. * @param model
  238. * @param id
  239. * @private
  240. */
  241. private getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
  242. const repository = this.getRepository(model)
  243. // Find the clone by id
  244. const entity = repository.find(this.CLONE_PREFIX + id)
  245. if (entity === null) {
  246. return null
  247. }
  248. // Restore the initial id
  249. entity.id = id
  250. return entity
  251. }
  252. }
  253. export default EntityManager