Skip to content

Commit

Permalink
feat: add default tx options
Browse files Browse the repository at this point in the history
  • Loading branch information
sam-artuso committed Apr 5, 2024
1 parent 753b592 commit 9799711
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pnpm add @nestjs-cls/transactional-adapter-pg-promise
## Registration

```ts
import { txMode } from 'pg-promise'

ClsModule.forRoot({
plugins: [
new ClsPluginTransactional({
Expand All @@ -42,6 +44,9 @@ ClsModule.forRoot({
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 }) }
}),
}),
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,20 @@ export interface PgPromiseTransactionalAdapterOptions {
* The injection token for the pg-promise instance.
*/
dbInstanceToken: any;

defaultTxOptions?: TxOptions;
}

export class TransactionalAdapterPgPromise
implements TransactionalAdapter<Database, Database, any>
{
connectionToken: any;

defaultTxOptions?: TxOptions;

constructor(options: PgPromiseTransactionalAdapterOptions) {
this.connectionToken = options.dbInstanceToken;
this.defaultTxOptions = options.defaultTxOptions;
}

optionsFactory = (pgPromiseDbInstance: Database) => ({
Expand All @@ -27,10 +32,13 @@ export class TransactionalAdapterPgPromise
fn: (...args: any[]) => Promise<any>,
setClient: (client?: Database) => void,
) => {
return pgPromiseDbInstance.tx(options ?? {}, (tx) => {
setClient(tx as unknown as Database);
return fn();
});
return pgPromiseDbInstance.tx(
options ?? this.defaultTxOptions ?? {},
(tx) => {
setClient(tx as unknown as Database);
return fn();
},
);
},
getFallbackInstance: () => pgPromiseDbInstance,
});
Expand Down

0 comments on commit 9799711

Please sign in to comment.