entityManager.test.ts 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. import { describe, test, vi, expect, beforeEach, afterEach } from 'vitest'
  2. import { Repository } from 'pinia-orm'
  3. import type { Element } from 'pinia-orm'
  4. import { Str, Uid } from 'pinia-orm/dist/decorators'
  5. import EntityManager from '~/services/data/entityManager'
  6. import ApiResource from '~/models/ApiResource'
  7. import ApiModel from '~/models/ApiModel'
  8. import ApiRequestService from '~/services/data/apiRequestService'
  9. import { IdField } from '~/models/decorators'
  10. class DummyApiResource extends ApiResource {
  11. static entity = 'dummyResource'
  12. @Uid()
  13. declare id: number | string
  14. @Str(null)
  15. declare name: string
  16. }
  17. class DummyApiModel extends ApiModel {
  18. static entity = 'dummyModel'
  19. @Uid()
  20. declare id: number | string
  21. @Str(null)
  22. declare name: string
  23. }
  24. class TestableEntityManager extends EntityManager {
  25. public _getProfileMask: () => object
  26. public removeTempAfterPersist(
  27. model: typeof ApiResource,
  28. tempInstanceId: number | string,
  29. ) {
  30. return super.removeTempAfterPersist(model, tempInstanceId)
  31. }
  32. public makeProfileHash() {
  33. return super.makeProfileHash()
  34. }
  35. public validateEntity(instance: unknown): void {
  36. return super.validateEntity(instance)
  37. }
  38. }
  39. const _console: any = {
  40. log: console.log,
  41. warn: console.warn,
  42. error: console.error,
  43. }
  44. vi.mock('~/models/models', async () => {
  45. class MyModel {
  46. static entity = 'my-model'
  47. }
  48. const modelsIndex: Record<string, any> = { 'my-model': () => MyModel }
  49. return {
  50. default: modelsIndex,
  51. }
  52. })
  53. let apiRequestService: ApiRequestService
  54. let entityManager: TestableEntityManager
  55. let repo: Repository<ApiResource>
  56. let _getRepo: (model: typeof ApiResource) => Repository<ApiResource>
  57. let _getProfileMask: () => object
  58. beforeEach(() => {
  59. // @ts-ignore
  60. repo = vi.fn() as Repository<ApiResource>
  61. // @ts-ignore
  62. apiRequestService = vi.fn() as ApiRequestService
  63. _getRepo = vi.fn((model: typeof ApiResource) => repo)
  64. _getProfileMask = vi.fn(() => {
  65. return {}
  66. })
  67. entityManager = new TestableEntityManager(
  68. apiRequestService,
  69. _getRepo,
  70. _getProfileMask,
  71. )
  72. })
  73. afterEach(() => {
  74. // Reset console methods after mock
  75. console.log = _console.log
  76. console.warn = _console.warn
  77. console.error = _console.error
  78. })
  79. describe('getRepository', () => {
  80. test('simple call', () => {
  81. entityManager.getRepository(DummyApiResource)
  82. expect(_getRepo).toHaveBeenCalledWith(DummyApiResource)
  83. })
  84. })
  85. describe('getQuery', () => {
  86. test('simple call', () => {
  87. // @ts-ignore
  88. const repo = vi.fn()
  89. // @ts-ignore
  90. entityManager.getRepository = vi.fn(() => repo)
  91. const query = vi.fn()
  92. // @ts-ignore
  93. repo.where = vi.fn((method) => {
  94. // Query method is supposed to exclude NaN ids values
  95. expect(method({ id: 123 })).toBeTruthy()
  96. expect(method({ id: 'abc' })).toBeFalsy()
  97. return query
  98. })
  99. const result = entityManager.getQuery(DummyApiResource)
  100. expect(result).toEqual(query)
  101. })
  102. })
  103. describe('cast', () => {
  104. test('simple cast', () => {
  105. // @ts-ignore
  106. const result = entityManager.cast(DummyApiResource, { id: 1 })
  107. expect(result instanceof DummyApiResource).toEqual(true)
  108. })
  109. })
  110. describe('getModelFor', () => {
  111. test('simple call', async () => {
  112. const model = await entityManager.getModelFor('my-model')
  113. expect(model!.entity).toEqual('my-model')
  114. })
  115. test('non existing model', async () => {
  116. expect(
  117. async () => await entityManager.getModelFor('non-existing-model'),
  118. ).rejects.toThrowError(
  119. "No model found for entity name 'non-existing-model'",
  120. )
  121. })
  122. })
  123. describe('getModelFromIri', () => {
  124. test('simple call', async () => {
  125. // @ts-ignore
  126. entityManager.getModelFor = vi.fn(
  127. async (entityName: string) => DummyApiResource,
  128. )
  129. // @ts-ignore
  130. const result = await entityManager.getModelFromIri('/api/dummy/123')
  131. console.log(result)
  132. expect(result).toEqual(DummyApiResource)
  133. })
  134. test('invalide Iri', () => {
  135. expect(
  136. async () => await entityManager.getModelFromIri('/invalid'),
  137. ).rejects.toThrowError('cannot parse the IRI')
  138. })
  139. })
  140. describe('newInstance', () => {
  141. test('simple call', () => {
  142. const properties = { id: 1 }
  143. // @ts-ignore
  144. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  145. return model === DummyApiResource ? repo : null
  146. })
  147. // @ts-ignore
  148. const entity = new DummyApiResource(properties)
  149. // @ts-ignore
  150. repo.make = vi.fn((properties: object) => {
  151. // @ts-ignore
  152. entity.id = properties.id
  153. return entity
  154. })
  155. // @ts-ignore
  156. entityManager.save = vi.fn(
  157. (entity: ApiResource, permanent: boolean) => entity,
  158. )
  159. const result = entityManager.newInstance(DummyApiResource, properties)
  160. expect(repo.make).toHaveBeenCalledWith(properties)
  161. expect(entityManager.save).toHaveBeenCalledWith(entity, true)
  162. expect(result.id).toEqual(properties.id)
  163. })
  164. test('with no id provided', () => {
  165. const properties = { name: 'bob' }
  166. // @ts-ignore
  167. const repo = vi.fn() as Repository<ApiResource>
  168. // @ts-ignore
  169. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  170. return model === DummyApiResource ? repo : null
  171. })
  172. // @ts-ignore
  173. entityManager.saveInitialState = vi.fn(
  174. (model: typeof ApiResource, entity: ApiResource) => null,
  175. )
  176. // @ts-ignore
  177. const entity = new DummyApiResource(properties)
  178. // @ts-ignore
  179. repo.make = vi.fn((properties: object) => {
  180. // @ts-ignore
  181. entity.name = properties.name
  182. return entity
  183. })
  184. // @ts-ignore
  185. repo.save = vi.fn((record: Element) => entity)
  186. const result = entityManager.newInstance(DummyApiResource, properties)
  187. expect(result.id, "id is 'tmp' followed by a valid uuid-V4").toMatch(
  188. /tmp[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}/,
  189. )
  190. expect(result.name).toEqual(properties.name)
  191. })
  192. })
  193. describe('save', () => {
  194. test('simple call', () => {
  195. // @ts-ignore
  196. const repo = vi.fn() as Repository<ApiResource>
  197. // @ts-ignore
  198. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  199. return model === DummyApiResource ? repo : null
  200. })
  201. entityManager.validateEntity = vi.fn((instance: unknown) => {})
  202. // @ts-ignore
  203. repo.save = vi.fn((record: Element) => entity)
  204. const entity = new DummyApiResource({ id: 1 })
  205. entityManager.save(entity)
  206. expect(entityManager.validateEntity).toHaveBeenCalledWith(entity)
  207. expect(repo.save).toHaveBeenCalledWith(entity)
  208. })
  209. })
  210. describe('find', () => {
  211. test('simple call', () => {
  212. // @ts-ignore
  213. const repo = vi.fn() as Repository<ApiResource>
  214. // @ts-ignore
  215. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  216. return model === DummyApiResource ? repo : null
  217. })
  218. const entity = new DummyApiResource({ id: 1 })
  219. // @ts-ignore
  220. repo.find = vi.fn((id: string | number) => entity)
  221. entityManager.find(DummyApiResource, 1)
  222. expect(entityManager.getRepository).toHaveBeenCalledWith(DummyApiResource)
  223. expect(repo.find).toHaveBeenCalledWith(1)
  224. })
  225. })
  226. describe('fetch', () => {
  227. test('not in store, no force refresh', async () => {
  228. const properties = { id: 1 }
  229. const entity = new DummyApiResource({ id: 1 })
  230. // @ts-ignore
  231. entityManager.find = vi.fn(
  232. (model: typeof ApiResource, id: number) => undefined,
  233. )
  234. // @ts-ignore
  235. apiRequestService.get = vi.fn(async (url: string) => properties)
  236. // @ts-ignore
  237. entityManager.newInstance = vi.fn(
  238. (model: typeof ApiResource, props: object) => entity,
  239. )
  240. const result = await entityManager.fetch(DummyApiResource, 1)
  241. expect(entityManager.find).toHaveBeenCalledWith(DummyApiResource, 1)
  242. expect(apiRequestService.get).toHaveBeenCalledWith('api/dummyResource/1')
  243. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiResource, {
  244. id: 1,
  245. name: null,
  246. _model: undefined,
  247. })
  248. expect(result).toEqual(entity)
  249. })
  250. test('in store, no force refresh', async () => {
  251. const properties = { id: 1 }
  252. const entity = new DummyApiResource({ id: 1 })
  253. // @ts-ignore
  254. entityManager.find = vi.fn(
  255. (model: typeof ApiResource, id: number) => entity,
  256. )
  257. const result = await entityManager.fetch(DummyApiResource, 1)
  258. expect(entityManager.find).toHaveBeenCalledWith(DummyApiResource, 1)
  259. expect(result).toEqual(entity)
  260. })
  261. test('in store, but with force refresh', async () => {
  262. const properties = { id: 1 }
  263. const entity = new DummyApiResource({ id: 1 })
  264. // @ts-ignore
  265. entityManager.find = vi.fn(
  266. (model: typeof ApiResource, id: number) => undefined,
  267. )
  268. // @ts-ignore
  269. apiRequestService.get = vi.fn(async (url: string) => properties)
  270. // @ts-ignore
  271. entityManager.newInstance = vi.fn(
  272. (model: typeof ApiResource, props: object) => entity,
  273. )
  274. const result = await entityManager.fetch(DummyApiResource, 1, true)
  275. expect(entityManager.find).toHaveBeenCalledTimes(0)
  276. expect(apiRequestService.get).toHaveBeenCalledWith('api/dummyResource/1')
  277. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiResource, {
  278. id: 1,
  279. name: null,
  280. _model: undefined,
  281. })
  282. expect(result).toEqual(entity)
  283. })
  284. })
  285. describe('fetchCollection', () => {
  286. test('simple call', async () => {
  287. const collection = {
  288. '@type': 'Collection',
  289. totalItems: 3,
  290. member: [{ id: 1 }, { id: 2 }, { id: 3 }],
  291. }
  292. // @ts-ignore
  293. apiRequestService.get = vi.fn(async (url: string) => collection)
  294. // @ts-ignore
  295. entityManager.newInstance = vi.fn(
  296. (model: typeof ApiResource, props: object) => {
  297. return new DummyApiResource(props)
  298. },
  299. )
  300. const piniaOrmQuery = vi.fn()
  301. // @ts-ignore
  302. entityManager.getQuery = vi.fn((model: typeof ApiResource) => piniaOrmQuery)
  303. const result = await entityManager.fetchCollection(DummyApiResource, null)
  304. expect(apiRequestService.get).toHaveBeenCalledWith('api/dummyResource')
  305. expect(entityManager.newInstance).toHaveBeenCalledTimes(3)
  306. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiResource, {
  307. id: 1,
  308. name: null,
  309. _model: undefined,
  310. })
  311. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiResource, {
  312. id: 2,
  313. name: null,
  314. _model: undefined,
  315. })
  316. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiResource, {
  317. id: 3,
  318. name: null,
  319. _model: undefined,
  320. })
  321. // @ts-ignore
  322. piniaOrmQuery.get = vi.fn(() => [
  323. new DummyApiResource({ id: 1 }),
  324. new DummyApiResource({ id: 2 }),
  325. new DummyApiResource({ id: 3 }),
  326. ])
  327. expect(result.value.items).toEqual([
  328. new DummyApiResource({ id: 1 }),
  329. new DummyApiResource({ id: 2 }),
  330. new DummyApiResource({ id: 3 }),
  331. ])
  332. expect(result.value.pagination, 'default pagination').toEqual({
  333. first: 1,
  334. last: 1,
  335. next: undefined,
  336. previous: undefined,
  337. })
  338. // @ts-expect-error Needed to avoid 'Cannot stringify non POJO' occasional bugs
  339. expect(result.toJSON()).toEqual(
  340. 'Computed result from fetchCollection at : api/dummyResource',
  341. )
  342. })
  343. test('with a parent', async () => {
  344. const collection = {
  345. '@type': 'Collection',
  346. totalItems: 3,
  347. member: [{ id: 1 }, { id: 2 }, { id: 3 }],
  348. }
  349. // @ts-ignore
  350. apiRequestService.get = vi.fn(async (url: string) => collection)
  351. const piniaOrmQuery = vi.fn()
  352. // @ts-ignore
  353. entityManager.getQuery = vi.fn((model: typeof ApiResource) => piniaOrmQuery)
  354. // @ts-ignore
  355. entityManager.newInstance = vi.fn(
  356. (model: typeof ApiResource, props: object) => {
  357. return new DummyApiResource(props)
  358. },
  359. )
  360. const parent = new DummyApiModel()
  361. parent.id = 100
  362. parent.entity = 'dummyModel' // TODO: je ne comprend pas pqoi cette ligne est nécessaire...
  363. await entityManager.fetchCollection(DummyApiResource, parent)
  364. expect(apiRequestService.get).toHaveBeenCalledWith(
  365. 'api/dummyModel/100/dummyResource',
  366. )
  367. })
  368. test('with a query', async () => {
  369. const collection = {
  370. '@type': 'Collection',
  371. totalItems: 3,
  372. member: [{ id: 1 }, { id: 2 }, { id: 3 }],
  373. }
  374. const query = vi.fn()
  375. // @ts-ignore
  376. query.getUrlQuery = vi.fn(() => 'foo=bar')
  377. // @ts-ignore
  378. query.applyToPiniaOrmQuery = vi.fn((q) => q)
  379. const piniaOrmQuery = vi.fn()
  380. // @ts-ignore
  381. entityManager.getQuery = vi.fn((model: typeof ApiResource) => piniaOrmQuery)
  382. // @ts-ignore
  383. apiRequestService.get = vi.fn(async (url: string) => collection)
  384. // @ts-ignore
  385. entityManager.newInstance = vi.fn(
  386. (model: typeof ApiResource, props: object) => {
  387. return new DummyApiResource(props)
  388. },
  389. )
  390. // @ts-ignore
  391. await entityManager.fetchCollection(DummyApiResource, null, query)
  392. expect(apiRequestService.get).toHaveBeenCalledWith(
  393. 'api/dummyResource?foo=bar',
  394. )
  395. // @ts-ignore
  396. expect(query.getUrlQuery).toHaveBeenCalledWith()
  397. // @ts-ignore
  398. expect(query.applyToPiniaOrmQuery).toHaveBeenCalledWith(piniaOrmQuery)
  399. })
  400. })
  401. describe('persist', () => {
  402. test('new entity (POST)', async () => {
  403. const instance = new DummyApiModel({ id: 'tmp1', name: 'bob' })
  404. instance.isNew = vi.fn(() => true)
  405. // @ts-ignore
  406. instance.$toJson = vi.fn(() => {
  407. return { id: 'tmp1', name: 'bob' }
  408. })
  409. // @ts-ignore
  410. entityManager.cast = vi.fn(
  411. (model: typeof ApiResource, entity: ApiResource): ApiResource => entity,
  412. )
  413. entityManager.validateEntity = vi.fn((instance: unknown) => {})
  414. const response = { id: 1, name: 'bob' }
  415. // @ts-ignore
  416. apiRequestService.post = vi.fn((url, data) => response)
  417. // @ts-ignore
  418. entityManager.newInstance = vi.fn((model, response) => {
  419. const newEntity = new DummyApiModel(response)
  420. // @ts-ignore
  421. newEntity.id = response.id
  422. // @ts-ignore
  423. newEntity.name = response.name
  424. return newEntity
  425. })
  426. // @ts-ignore
  427. entityManager.removeTempAfterPersist = vi.fn()
  428. entityManager.makeProfileHash = vi.fn(async () => await 'azerty')
  429. const result = await entityManager.persist(instance)
  430. // temp id should have been purged from the posted data
  431. expect(apiRequestService.post).toHaveBeenCalledWith(
  432. 'api/dummyModel',
  433. {
  434. name: 'bob',
  435. },
  436. null,
  437. { profileHash: 'azerty' },
  438. )
  439. expect(entityManager.newInstance).toHaveBeenCalledWith(
  440. DummyApiModel,
  441. response,
  442. )
  443. // @ts-ignore
  444. expect(entityManager.removeTempAfterPersist).toHaveBeenCalledWith(
  445. DummyApiModel,
  446. instance.id,
  447. )
  448. // @ts-ignore
  449. expect(entityManager.makeProfileHash).toHaveBeenCalledTimes(1)
  450. expect(result.id).toEqual(1)
  451. expect(result.name).toEqual('bob')
  452. expect(entityManager.validateEntity).toHaveBeenCalledWith(instance)
  453. })
  454. test('existing entity (PUT)', async () => {
  455. const props = { id: 1, name: 'bob' }
  456. const entity = new DummyApiModel(props)
  457. entity.id = 1
  458. entity.isNew = vi.fn(() => false)
  459. // @ts-ignore
  460. entity.$toJson = vi.fn(() => props)
  461. // TODO: attendre de voir si cet appel est nécessaire dans l'entity manager
  462. // entityManager.cast = vi.fn((model: typeof ApiResource, entity: ApiResource): ApiResource => entity)
  463. // @ts-ignore
  464. apiRequestService.patch = vi.fn((url, data) => props)
  465. // @ts-ignore
  466. entityManager.newInstance = vi.fn((model, response) => {
  467. const newEntity = new DummyApiModel(response)
  468. // @ts-ignore
  469. newEntity.id = response.id
  470. // @ts-ignore
  471. newEntity.name = response.name
  472. return newEntity
  473. })
  474. // @ts-ignore
  475. entityManager.removeTempAfterPersist = vi.fn()
  476. entityManager.makeProfileHash = vi.fn(async () => await 'azerty')
  477. entityManager.validateEntity = vi.fn((instance: unknown) => {})
  478. const result = await entityManager.persist(entity)
  479. expect(apiRequestService.patch).toHaveBeenCalledWith(
  480. 'api/dummyModel/1',
  481. {
  482. id: 1,
  483. name: 'bob',
  484. },
  485. null,
  486. { profileHash: 'azerty' },
  487. )
  488. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiModel, props)
  489. // @ts-ignore
  490. expect(entityManager.removeTempAfterPersist).toHaveBeenCalledTimes(0)
  491. // @ts-ignore
  492. expect(entityManager.makeProfileHash).toHaveBeenCalledTimes(1)
  493. expect(result.id).toEqual(1)
  494. expect(result.name).toEqual('bob')
  495. expect(entityManager.validateEntity).toHaveBeenCalledWith(entity)
  496. })
  497. })
  498. describe('patch', () => {
  499. test('simple call', async () => {
  500. const props = { id: 1, name: 'bobby' }
  501. // @ts-ignore
  502. apiRequestService.put = vi.fn((url, data) => props)
  503. // @ts-ignore
  504. entityManager.newInstance = vi.fn((model, response) => {
  505. const newEntity = new DummyApiModel(response)
  506. // @ts-ignore
  507. newEntity.id = response.id
  508. // @ts-ignore
  509. newEntity.name = response.name
  510. return newEntity
  511. })
  512. const result = await entityManager.patch(DummyApiModel, 1, {
  513. name: 'bobby',
  514. })
  515. expect(apiRequestService.put).toHaveBeenCalledWith(
  516. 'api/dummyModel/1',
  517. '{"name":"bobby"}',
  518. )
  519. expect(entityManager.newInstance).toHaveBeenCalledWith(DummyApiModel, {
  520. id: 1,
  521. name: 'bobby',
  522. })
  523. expect(result.id).toEqual(1)
  524. expect(result.name).toEqual('bobby')
  525. })
  526. })
  527. describe('delete', () => {
  528. test('delete non persisted entity', () => {
  529. const entity = new DummyApiModel()
  530. entity.id = 'tmp123'
  531. // @ts-ignore
  532. const repo = vi.fn() as Repository<ApiResource>
  533. // @ts-ignore
  534. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  535. return model === DummyApiModel ? repo : null
  536. })
  537. entityManager.validateEntity = vi.fn((instance: unknown) => {})
  538. apiRequestService.delete = vi.fn()
  539. // @ts-ignore
  540. repo.destroy = vi.fn((id: number) => null)
  541. entityManager.delete(entity)
  542. expect(entityManager.getRepository).toHaveBeenCalledWith(DummyApiModel)
  543. expect(apiRequestService.delete).toHaveBeenCalledTimes(0)
  544. expect(repo.destroy).toHaveBeenCalledWith('tmp123')
  545. expect(entityManager.validateEntity).toHaveBeenCalledWith(entity)
  546. })
  547. test('delete persisted entity', async () => {
  548. const entity = new DummyApiModel()
  549. entity.isNew = vi.fn(() => false)
  550. entity.id = 1
  551. // @ts-ignore
  552. const repo = vi.fn() as Repository<ApiResource>
  553. // @ts-ignore
  554. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  555. return model === DummyApiModel ? repo : null
  556. })
  557. // @ts-ignore
  558. apiRequestService.delete = vi.fn((id: number) => null)
  559. // @ts-ignore
  560. repo.destroy = vi.fn((id: number) => null)
  561. await entityManager.delete(entity)
  562. expect(entityManager.getRepository).toHaveBeenCalledWith(DummyApiModel)
  563. expect(apiRequestService.delete).toHaveBeenCalledWith('api/dummyModel/1')
  564. expect(repo.destroy).toHaveBeenCalledWith(1)
  565. })
  566. })
  567. describe('reset', () => {
  568. test('simple call', () => {
  569. const entity = new DummyApiModel()
  570. entity.id = 1
  571. entity.name = 'paul'
  572. const initialEntity = new DummyApiModel()
  573. initialEntity.id = 1
  574. initialEntity.name = 'serge'
  575. // @ts-ignore
  576. entityManager.getInitialStateOf = vi.fn(
  577. (model: typeof ApiResource, id: string | number) => initialEntity,
  578. )
  579. // @ts-ignore
  580. const repo = vi.fn() as Repository<ApiResource>
  581. // @ts-ignore
  582. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  583. return model === DummyApiModel ? repo : null
  584. })
  585. // @ts-ignore
  586. repo.save = vi.fn((data: any) => null)
  587. const result = entityManager.reset(initialEntity)
  588. // @ts-ignore
  589. expect(entityManager.getInitialStateOf).toHaveBeenCalledWith(
  590. DummyApiModel,
  591. 1,
  592. )
  593. expect(repo.save).toHaveBeenCalledWith(initialEntity)
  594. expect(result).toEqual(initialEntity)
  595. })
  596. test('no initial state stored', () => {
  597. const entity = new DummyApiModel()
  598. entity.id = 1
  599. // @ts-ignore
  600. entityManager.getInitialStateOf = vi.fn(
  601. (model: typeof ApiResource, id: string | number) => null,
  602. )
  603. // @ts-ignore
  604. entityManager.getModel = vi.fn((instance: ApiResource) => DummyApiModel)
  605. expect(() => entityManager.reset(entity)).toThrowError(
  606. 'no initial state recorded for this object - abort [dummyModel/1]',
  607. )
  608. })
  609. })
  610. describe('flush', () => {
  611. test('simple call', () => {
  612. // @ts-ignore
  613. const repo = vi.fn() as Repository<ApiResource>
  614. // @ts-ignore
  615. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  616. return model === DummyApiModel ? repo : null
  617. })
  618. repo.flush = vi.fn()
  619. entityManager.flush(DummyApiModel)
  620. expect(repo.flush).toHaveBeenCalled()
  621. })
  622. })
  623. describe('isNewEntity', () => {
  624. test('with new entity', () => {
  625. const entity = new DummyApiModel()
  626. entity.isNew = vi.fn(() => true)
  627. // @ts-ignore
  628. const repo = vi.fn() as Repository<ApiResource>
  629. // @ts-ignore
  630. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  631. return model === DummyApiModel ? repo : null
  632. })
  633. // @ts-ignore
  634. repo.find = vi.fn((id: number) => entity)
  635. const result = entityManager.isNewInstance(DummyApiModel, 1)
  636. expect(result).toBeTruthy()
  637. })
  638. test('with existing entity', () => {
  639. const entity = new DummyApiModel()
  640. entity.isNew = vi.fn(() => false)
  641. // @ts-ignore
  642. const repo = vi.fn() as Repository<ApiResource>
  643. // @ts-ignore
  644. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  645. return model === DummyApiModel ? repo : null
  646. })
  647. // @ts-ignore
  648. repo.find = vi.fn((id: number) => entity)
  649. const result = entityManager.isNewInstance(DummyApiModel, 1)
  650. expect(result).toBeFalsy()
  651. })
  652. test('non-existing entity', () => {
  653. // @ts-ignore
  654. const repo = vi.fn() as Repository<ApiResource>
  655. // @ts-ignore
  656. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  657. return model === DummyApiModel ? repo : null
  658. })
  659. // @ts-ignore
  660. repo.find = vi.fn((id: number) => null)
  661. console.error = vi.fn()
  662. const result = entityManager.isNewInstance(DummyApiModel, 1)
  663. expect(result).toBeFalsy()
  664. expect(console.error).toHaveBeenCalledWith('dummyModel/1 does not exist!')
  665. })
  666. })
  667. describe('saveInitialState', () => {
  668. test('simple call', () => {
  669. // @ts-ignore
  670. const entity = { id: 1, name: 'bob' } as DummyApiResource
  671. // @ts-ignore
  672. const repo = vi.fn() as Repository<ApiResource>
  673. // @ts-ignore
  674. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  675. return model === DummyApiResource ? repo : null
  676. })
  677. // @ts-ignore
  678. repo.save = vi.fn((record: Element) => null)
  679. // @ts-ignore
  680. entityManager.saveInitialState(DummyApiResource, entity)
  681. expect(repo.save).toHaveBeenCalledWith({ id: '_clone_1', name: 'bob' })
  682. expect(entity.id).toEqual(1)
  683. })
  684. })
  685. describe('getInitialStateOf', () => {
  686. test('with initial state', () => {
  687. // @ts-ignore
  688. const entity = { id: 1, name: 'bob' } as DummyApiResource
  689. // @ts-ignore
  690. const repo = vi.fn() as Repository<ApiResource>
  691. // @ts-ignore
  692. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  693. return model === DummyApiResource ? repo : null
  694. })
  695. // @ts-ignore
  696. repo.find = vi.fn((id: number | string) => {
  697. // @ts-ignore
  698. return { id: 1, name: 'robert' } as DummyApiResource
  699. })
  700. // @ts-ignore
  701. const result = entityManager.getInitialStateOf(
  702. DummyApiResource,
  703. 1,
  704. ) as DummyApiResource
  705. expect(repo.find).toHaveBeenCalledWith('_clone_1')
  706. expect(result.id).toEqual(1)
  707. expect(result.name).toEqual('robert')
  708. })
  709. test('without initial state', () => {
  710. // @ts-ignore
  711. const repo = vi.fn() as Repository<ApiResource>
  712. // @ts-ignore
  713. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  714. return model === DummyApiResource ? repo : null
  715. })
  716. // @ts-ignore
  717. repo.find = vi.fn((id: number | string) => null)
  718. // @ts-ignore
  719. const result = entityManager.getInitialStateOf(
  720. DummyApiResource,
  721. 1,
  722. ) as DummyApiResource
  723. expect(repo.find).toHaveBeenCalledWith('_clone_1')
  724. expect(result).toEqual(null)
  725. })
  726. })
  727. describe('removeTempAfterPersist', () => {
  728. test('simple call', () => {
  729. // @ts-ignore
  730. const entity = new DummyApiResource()
  731. entity.id = 'tmp123'
  732. entity.isNew = vi.fn(() => true)
  733. // @ts-ignore
  734. const repo = vi.fn() as Repository<ApiResource>
  735. // @ts-ignore
  736. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  737. return model === DummyApiResource ? repo : null
  738. })
  739. // @ts-ignore
  740. repo.find = vi.fn((id: number | string) => entity)
  741. // @ts-ignore
  742. repo.destroy = vi.fn()
  743. // @ts-ignore
  744. entityManager.removeTempAfterPersist(DummyApiResource, 'tmp123')
  745. expect(repo.destroy).toHaveBeenCalledWith('tmp123')
  746. expect(repo.destroy).toHaveBeenCalledWith('_clone_tmp123')
  747. })
  748. test('entity is not temporary', () => {
  749. // @ts-ignore
  750. const entity = new DummyApiResource()
  751. entity.id = 1
  752. entity.isNew = vi.fn(() => false)
  753. // @ts-ignore
  754. const repo = vi.fn() as Repository<ApiResource>
  755. // @ts-ignore
  756. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  757. return model === DummyApiResource ? repo : null
  758. })
  759. // @ts-ignore
  760. repo.find = vi.fn((id: number | string) => entity)
  761. // @ts-ignore
  762. repo.destroy = vi.fn()
  763. // @ts-ignore
  764. expect(() =>
  765. entityManager.removeTempAfterPersist(DummyApiResource, 'tmp123'),
  766. ).toThrowError('Error: Can not remove a non-temporary model instance')
  767. expect(repo.destroy).toHaveBeenCalledTimes(0)
  768. })
  769. test('entity does not exist', () => {
  770. // @ts-ignore
  771. const repo = vi.fn() as Repository<ApiResource>
  772. // @ts-ignore
  773. entityManager.getRepository = vi.fn((model: typeof ApiResource) => {
  774. return model === DummyApiResource ? repo : null
  775. })
  776. // @ts-ignore
  777. repo.find = vi.fn((id: number | string) => null)
  778. // @ts-ignore
  779. repo.destroy = vi.fn()
  780. console.error = vi.fn()
  781. // @ts-ignore
  782. entityManager.removeTempAfterPersist(DummyApiResource, 'tmp123')
  783. expect(repo.destroy).toHaveBeenCalledTimes(0)
  784. expect(console.error).toHaveBeenCalledWith(
  785. 'dummyResource/tmp123 does not exist!',
  786. )
  787. })
  788. })
  789. describe('makeProfileHash', () => {
  790. test('simple call', async () => {
  791. entityManager._getProfileMask = vi.fn(() => {
  792. return { a: 1 }
  793. })
  794. expect(await entityManager.makeProfileHash()).toEqual(
  795. '9f89c740ceb46d7418c924a78ac57941d5e96520',
  796. )
  797. })
  798. })
  799. describe('validateEntity', () => {
  800. test('instance with numeric id', async () => {
  801. entityManager.validateEntity({ id: 123 })
  802. })
  803. test('instance with temp id', async () => {
  804. entityManager.validateEntity({ id: 'tmpazerty' })
  805. })
  806. test('invalid entity', async () => {
  807. expect(() => entityManager.validateEntity({ id: 'azerty' })).toThrowError(
  808. 'Definition error for the entity, did you use the entityManager.newInstance(...) method?\n{"id":"azerty"}',
  809. )
  810. })
  811. })