Приветствую.
В сервисе создаю коннект connection для queryRunner:
constructor(
@InjectRepository(User) private readonly usersRepository: Repository<User>,
@InjectRepository(SmsCodes) private readonly smsCodesRepository: Repository<SmsCodes>,
@InjectRepository(Partners) private readonly partnersRepository: Repository<Partners>,
private connection: Connection,
) {}
В методе использую queryRunner для транзакций с выше объявленным connection:
async createUser (userParams) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const newPartner = this.partnersRepository.create({
company: userParams.company,
created: Math.floor(Date.now() / 1000),
updated: Math.floor(Date.now() / 1000),
});
const getNewPartner = await this.partnersRepository.save(newPartner);
const newUser = this.usersRepository.create({
partnerId: getNewPartner.id,
name: userParams.name,
phone: userParams.phone,
email: userParams.email,
password: '112233',
role: 'partner',
created: Math.floor(Date.now() / 1000),
updated: Math.floor(Date.now() / 1000),
});
await this.usersRepository.save(newUser);
await queryRunner.commitTransaction();
return true;
} catch (error) {
await queryRunner.rollbackTransaction();
return false;
} finally {
await queryRunner.release();
}
}
В тесте делаю соединение с тестовой базой данных:
let usersService: UsersService;
let usersRepository: Repository<User>;
let smsCodesRepository: Repository<SmsCodes>;
let partnersRepository: Repository<Partners>
let testingModule: TestingModule;
const testConnectionName = 'testConnection';
beforeEach(async () => {
let connection = await createConnection({
type: "postgres",
database: "baseTest",
host: process.env.POSTGRES_HOST,
port: +process.env.POSTGRES_PORT,
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
dropSchema: true,
entities: [User, SmsCodes, Partners],
synchronize: true,
logging: false,
name: testConnectionName
});
testingModule = await Test.createTestingModule({
imports: [],
providers: [
UsersService,
{
provide: getRepositoryToken(User),
useClass: Repository,
},
{
provide: getRepositoryToken(SmsCodes),
useClass: Repository,
},
{
provide: getRepositoryToken(Partners),
useClass: Repository,
},
{
provide: Connection,
useClass: Connection
},
],
}).compile();
usersRepository = getRepository(User, testConnectionName);
smsCodesRepository = getRepository(SmsCodes, testConnectionName);
partnersRepository = getRepository(Partners, testConnectionName);
usersService = new UsersService(usersRepository, smsCodesRepository, partnersRepository, connection);
return connection;
});
Как правильно передать connection в Класс сервиса?
Потому что сейчас выдаёт ошибку:
TypeError: Cannot read property 'name' of undefined
Если убираю соединение, то все работает(остальные тесты где функции не используют queryRunner).