Skip to main content

Pg-promise adapter

Installation

npm install @nestjs-cls/transactional-adapter-pg-promise

Registration

import { txMode } from 'pg-promise'

ClsModule.forRoot({
plugins: [
new ClsPluginTransactional({
imports: [
// module in which the database instance is provided
DbModule
],
adapter: new TransactionalAdapterPgPromise({
// the injection token of the database instance
dbInstanceToken: DB,

// default transaction options (optional)
defaultTxOptions: { mode: new txMode.TransactionMode({ tiLevel: txMode.isolationLevel.serializable }) }
}),
}),
],
}),

Typing & usage

The tx property on the TransactionHost<TransactionalAdapterPgPromise> is typed as Database.

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',
'john@acme.com',
);
const foundUser = await this.userRepository.getUserById(user.id);
assert(foundUser.id === user.id);
}
}
user.repository.ts
@Injectable()
class UserRepository {
constructor(
private readonly txHost: TransactionHost<TransactionalAdapterPgPromise>,
) {}

async getUserById(id: number) {
// txHost.tx is typed as Database
return this.txHost.tx.one(`SELECT * FROM user WHERE id = $1`, [id]);
}

async createUser(name: string, email: string) {
return this.txHost.tx.none(
`INSERT INTO user (name, email) VALUES ($1, $2)`,
[name, email],
);
}
}