entityManager.ts 8.5 KB

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