entityManager.test.ts 27 KB

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