entityManager.ts 9.4 KB

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