Skip to main content

Knex adapter

Installation

npm install @nestjs-cls/transactional-adapter-knex

Registration

ClsModule.forRoot({
plugins: [
new ClsPluginTransactional({
imports: [
// module in which the Knex is provided
KnexModule
],
adapter: new TransactionalAdapterKnex({
// the injection token of the Knex client
knexInstanceToken: KNEX,
}),
}),
],
}),

Typing & usage

The tx property on the TransactionHost<TransactionalAdapterKnex> is typed as Knex.

Example

user.service.ts
@Injectable()
class UserService {
constructor(private readonly userRepository: UserRepository) {}

@Transactional()
async runTransaction() {
// both methods are executed in the same transaction
const user = await this.userRepository.createUser('John');
const foundUser = await this.userRepository.getUserById(r1.id);
assert(foundUser.id === user.id);
}
}
user.repository.ts
@Injectable()
class UserRepository {
constructor(
private readonly txHost: TransactionHost<TransactionalAdapterKnex>,
) {}

async getUserById(id: number) {
// txHost.tx is typed as Knex
return this.txHost.tx('user').where({ id }).first();
}

async createUser(name: string) {
return this.txHost
.tx('user')
.insert({ name: name, email: `${name}@email.com` })
.returning('*');
}
}