/
databse.ts
33 lines (27 loc) · 938 Bytes
/
databse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { INestApplication } from '@nestjs/common';
import { getDataSourceToken, getRepositoryToken } from '@nestjs/typeorm';
import { DataSource, EntityManager, Repository } from 'typeorm';
class RollbackError extends Error {}
export const withCleanup = async (
app: INestApplication<any>,
cb: (em: EntityManager) => Promise<void>,
) => {
const dataSource = app.get(getDataSourceToken());
const manager = dataSource.createEntityManager();
try {
await manager.transaction(async (em) => {
const dataSource: DataSource = app.get(getDataSourceToken());
jest.replaceProperty(dataSource, 'manager', em);
await cb(em);
throw new RollbackError('rollback');
});
} catch (e) {
if (e instanceof RollbackError) {
return;
}
throw e;
}
};
export const getRepository = <T>(app: INestApplication<any>, token: any) => {
return app.get(getRepositoryToken(token)) as Repository<T>;
};