entityManager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import ApiRequestService from "./apiRequestService"
  2. import {Repository} from "pinia-orm"
  3. import UrlUtils from "~/services/utils/urlUtils"
  4. import HydraDenormalizer from "./normalizer/hydraDenormalizer"
  5. import ApiModel from "~/models/ApiModel"
  6. import ApiResource from "~/models/ApiResource"
  7. import MyProfile from "~/models/Access/MyProfile"
  8. import {v4 as uuid4} from 'uuid'
  9. import {AssociativeArray, Collection} from "~/types/data.d"
  10. import models from "~/models/models";
  11. import {useAccessProfileStore} from "~/stores/accessProfile"
  12. import * as _ from "lodash-es"
  13. /**
  14. * Entity manager: make operations on the models defined with the Pinia-Orm library
  15. *
  16. * TODO: améliorer le typage des méthodes sur le modèle de find()
  17. * @see https://pinia-orm.codedredd.de/
  18. */
  19. class EntityManager {
  20. protected CLONE_PREFIX = '_clone_'
  21. /**
  22. * In instance of ApiRequestService
  23. * @protected
  24. */
  25. protected apiRequestService: ApiRequestService
  26. /**
  27. * A method to retrieve the repository of a given ApiResource
  28. * @protected
  29. */
  30. protected _getRepo: (model: typeof ApiResource) => Repository<ApiResource>
  31. public constructor(
  32. apiRequestService: ApiRequestService,
  33. getRepo: (model: typeof ApiResource) => Repository<ApiResource>
  34. ) {
  35. this.apiRequestService = apiRequestService
  36. this._getRepo = getRepo
  37. }
  38. /**
  39. * Return the repository for the model
  40. *
  41. * @param model
  42. */
  43. public getRepository(model: typeof ApiResource): Repository<ApiResource> {
  44. return this._getRepo(model)
  45. }
  46. /**
  47. * Cast an object as an ApiResource
  48. * This in used internally to ensure the object is recognized as an ApiResource
  49. *
  50. * @param model
  51. * @param instance
  52. * @protected
  53. */
  54. // noinspection JSMethodCanBeStatic
  55. protected cast(model: typeof ApiResource, instance: ApiResource): ApiResource {
  56. return new model(instance)
  57. }
  58. /**
  59. * Return the model class with the given entity name
  60. *
  61. * @param entityName
  62. */
  63. public getModelFor(entityName: string): typeof ApiResource {
  64. return models[entityName]
  65. }
  66. /**
  67. * Return the model class from an Opentalent Api IRI
  68. *
  69. * @param iri An IRI of the form .../api/<entity>/...
  70. */
  71. public getModelFromIri(iri: string): typeof ApiResource {
  72. const matches = iri.match(/^\/api\/(\w+)\/.*/)
  73. if (!matches || !matches[1]) {
  74. throw new Error('cannot parse the IRI')
  75. }
  76. return this.getModelFor(matches[1])
  77. }
  78. /**
  79. * Create a new instance of the given model
  80. *
  81. * @param model
  82. * @param properties
  83. */
  84. public newInstance(model: typeof ApiResource, properties: object = {}): ApiResource {
  85. const repository = this.getRepository(model)
  86. let instance = repository.make(properties)
  87. // Keep track of the model
  88. // TODO : attendre de voir si utile ou non
  89. // instance.setModel(model)
  90. // @ts-ignore
  91. if (!properties.hasOwnProperty('id') || !properties.id) {
  92. // Object has no id yet, we give him a temporary one
  93. instance.id = 'tmp' + uuid4()
  94. }
  95. return this.save(model, instance, true)
  96. }
  97. /**
  98. * Save the model instance into the store
  99. *
  100. * @param model
  101. * @param instance
  102. * @param permanent Is the change already persisted in the datasource? If this is the case, the initial state of this
  103. * record is also updated.
  104. */
  105. public save(model: typeof ApiResource, instance: ApiResource, permanent: boolean = false): ApiResource {
  106. instance = this.cast(model, instance)
  107. if (permanent) {
  108. this.saveInitialState(model, instance)
  109. }
  110. return this.getRepository(model).save(instance)
  111. }
  112. /**
  113. * Find the model instance in the store
  114. * TODO: comment réagit la fonction si l'id n'existe pas dans le store?
  115. *
  116. * @param model
  117. * @param id
  118. */
  119. // @ts-ignore
  120. public find<T extends ApiResource>(model: typeof T, id: number): T {
  121. const repository = this.getRepository(model)
  122. return repository.find(id) as T
  123. }
  124. /**
  125. * Fetch an ApiModel / ApiResource by its id, save it to the store and returns it
  126. *
  127. * @param model Model of the object to fetch
  128. * @param id Id of the object to fetch
  129. * @param forceRefresh Force a new get request to the api ;
  130. * current object in store will be overwritten if it exists
  131. */
  132. public async fetch(model: typeof ApiResource, id: number, forceRefresh: boolean = false): Promise<ApiResource> {
  133. // If the model instance is already in the store and forceRefresh is false, return the object in store
  134. if (!forceRefresh) {
  135. const item = this.find(model, id)
  136. if (item && typeof item !== 'undefined') {
  137. return item
  138. }
  139. }
  140. // Else, get the object from the API
  141. const url = UrlUtils.join('api', model.entity, String(id))
  142. const response = await this.apiRequestService.get(url)
  143. // deserialize the response
  144. const attributes = HydraDenormalizer.denormalize(response).data as object
  145. return this.newInstance(model, attributes)
  146. }
  147. /**
  148. * Fetch a collection of model instances
  149. * The content of `query` is converted into a query-string in the request URL
  150. *
  151. * @param model
  152. * @param query
  153. * @param parent
  154. */
  155. public async fetchCollection(model: typeof ApiResource, parent: ApiResource | null, query: AssociativeArray | null = null): Promise<Collection> {
  156. let url
  157. if (parent !== null) {
  158. url = UrlUtils.join('api', parent.entity, '' + parent.id, model.entity)
  159. } else {
  160. url = UrlUtils.join('api', model.entity)
  161. }
  162. const response = await this.apiRequestService.get(url, query)
  163. // deserialize the response
  164. const apiCollection = HydraDenormalizer.denormalize(response)
  165. const items = apiCollection.data.map((attributes: object) => {
  166. return this.newInstance(model, attributes)
  167. })
  168. return {
  169. items,
  170. totalItems: apiCollection.metadata.totalItems,
  171. pagination: {
  172. first: apiCollection.metadata.firstPage || 1,
  173. last: apiCollection.metadata.lastPage || 1,
  174. next: apiCollection.metadata.nextPage || undefined,
  175. previous: apiCollection.metadata.previousPage || undefined,
  176. }
  177. }
  178. }
  179. /**
  180. * Persist the model instance as it is in the store into the data source via the API
  181. *
  182. * @param model
  183. * @param instance
  184. */
  185. public async persist(model: typeof ApiModel, instance: ApiModel) {
  186. // Recast in case class definition has been "lost"
  187. // TODO: attendre de voir si cette ligne est nécessaire
  188. // instance = this.cast(model, instance)
  189. let url = UrlUtils.join('api', model.entity)
  190. let response
  191. const data: any = instance.$toJson()
  192. if (!instance.isNew()) {
  193. url = UrlUtils.join(url, String(instance.id))
  194. response = await this.apiRequestService.put(url, data)
  195. } else {
  196. delete data.id
  197. response = await this.apiRequestService.post(url, data)
  198. }
  199. const hydraResponse = await HydraDenormalizer.denormalize(response)
  200. const newInstance = this.newInstance(model, hydraResponse.data)
  201. // Si l'instance était nouvelle avant d'être persistée, elle vient désormais de recevoir un id définitif. On
  202. // peut donc supprimer l'instance temporaire.
  203. if (instance.isNew()) {
  204. this.removeTempAfterPersist(model, instance.id)
  205. }
  206. return newInstance
  207. }
  208. /**
  209. * Send an update request (PUT) to the API with the given data on an existing model instance
  210. *
  211. * @param model
  212. * @param id
  213. * @param data
  214. */
  215. public async patch(model: typeof ApiModel, id: number, data: AssociativeArray) {
  216. let url = UrlUtils.join('api', model.entity, ''+id)
  217. const body = JSON.stringify(data)
  218. const response = await this.apiRequestService.put(url, body)
  219. const hydraResponse = await HydraDenormalizer.denormalize(response)
  220. return this.newInstance(model, hydraResponse.data)
  221. }
  222. /**
  223. * Delete the model instance from the datasource via the API
  224. *
  225. * @param model
  226. * @param instance
  227. */
  228. public async delete(model: typeof ApiModel, instance: ApiResource) {
  229. const repository = this.getRepository(model)
  230. // If object has been persisted to the datasource, send a delete request
  231. if (!instance.isNew()) {
  232. const url = UrlUtils.join('api', model.entity, String(instance.id))
  233. await this.apiRequestService.delete(url)
  234. }
  235. // reactiveUpdate the store
  236. repository.destroy(instance.id)
  237. }
  238. /**
  239. * Reset the model instance to its initial state (i.e. the state it had when it was fetched from the API)
  240. *
  241. * @param model
  242. * @param instance
  243. */
  244. public reset(model: typeof ApiResource, instance: ApiResource) {
  245. const initialInstance = this.getInitialStateOf(model, instance.id)
  246. if (initialInstance === null) {
  247. throw new Error('no initial state recorded for this object - abort [' + model.entity + '/' + instance.id + ']')
  248. }
  249. const repository = this.getRepository(model)
  250. repository.save(initialInstance)
  251. return initialInstance
  252. }
  253. /**
  254. * Delete all records in the repository of the model
  255. *
  256. * @param model
  257. */
  258. public flush(model: typeof ApiModel) {
  259. const repository = this.getRepository(model)
  260. repository.flush()
  261. }
  262. /**
  263. * Is the model instance a new one, or does it already exist in the data source (=API)
  264. *
  265. * This is a convenient way of testing a model instance you did not already fetch, else prefer the use of the
  266. * isNew() method of ApiResource
  267. *
  268. * @param model
  269. * @param id
  270. */
  271. public isNewInstance(model: typeof ApiModel, id: number | string): boolean {
  272. const repository = this.getRepository(model)
  273. const item = repository.find(id)
  274. if (!item || typeof item === 'undefined') {
  275. // TODO: est-ce qu'il ne faudrait pas lever une erreur ici plutôt?
  276. console.error(model.entity + '/' + id + ' does not exist!')
  277. return false
  278. }
  279. return item.isNew()
  280. }
  281. /**
  282. * Save the state of the model instance in the store, so this state could be restored later
  283. *
  284. * @param model
  285. * @param instance
  286. * @private
  287. */
  288. protected saveInitialState(model: typeof ApiResource, instance: ApiResource) {
  289. const repository = this.getRepository(model)
  290. // Clone and prefix id
  291. const clone = _.cloneDeep(instance)
  292. clone.id = this.CLONE_PREFIX + clone.id
  293. repository.save(clone)
  294. }
  295. /**
  296. * Return the saved state of the model instance from the store
  297. *
  298. * @param model
  299. * @param id
  300. * @private
  301. */
  302. protected getInitialStateOf(model: typeof ApiResource, id: string | number): ApiResource | null {
  303. const repository = this.getRepository(model)
  304. // Find the clone by id
  305. const instance = repository.find(this.CLONE_PREFIX + id)
  306. if (instance === null) {
  307. return null
  308. }
  309. // Restore the initial id
  310. instance.id = id
  311. return instance
  312. }
  313. /**
  314. * Delete the temporary model instance from the repo after it was persisted via the api, replaced by the instance
  315. * that has been returned by the api with is definitive id.
  316. *
  317. * @param model
  318. * @param tempInstanceId
  319. * @private
  320. */
  321. protected removeTempAfterPersist(model: typeof ApiResource, tempInstanceId: number | string) {
  322. const repository = this.getRepository(model)
  323. const instance = repository.find(tempInstanceId)
  324. if (!instance || typeof instance === 'undefined') {
  325. // TODO: il vaudrait peut-être mieux lever une erreur ici?
  326. console.error(model.entity + '/' + tempInstanceId + ' does not exist!')
  327. return
  328. }
  329. if (!instance.isNew()) {
  330. throw new Error('Error: Can not remove a non-temporary model instance')
  331. }
  332. repository.destroy(tempInstanceId)
  333. repository.destroy(this.CLONE_PREFIX + tempInstanceId)
  334. }
  335. }
  336. export default EntityManager