entityManager.test.ts 24 KB

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