entityManager.ts 9.5 KB

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