Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add @nestjs-cls/transactional-adapter-pg-promise #110

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# pg-promise adapter

## Installation

<Tabs>
<TabItem value="npm" label="npm" default>

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

</TabItem>
<TabItem value="yarn" label="yarn">

```bash
yarn add @nestjs-cls/transactional-adapter-pg-promise
```

</TabItem>
<TabItem value="pnpm" label="pnpm">

```bash
pnpm add @nestjs-cls/transactional-adapter-pg-promise
```

</TabItem>
</Tabs>

## Registration

```ts
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,
}),
}),
],
}),
```

## Typing & usage

The `tx` property on the `TransactionHost<TransactionalAdapterPgPromise>` is typed as [`Database`](https://vitaly-t.github.io/pg-promise/Database.html).

## Example

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

@Transactional()
async runTransaction() {
// highlight-start
// both methods are executed in the same transaction
const user = await this.userRepository.createUser(
'John',
'john@acme.com',
);
const foundUser = await this.userRepository.getUserById(r1.id);
// highlight-end
assert(foundUser.id === user.id);
}
}
```

```ts title="user.repository.ts"
@Injectable()
class UserRepository {
constructor(
private readonly txHost: TransactionHost<TransactionalAdapterPgPromise>,
) {}

async getUserById(id: number) {
// highlight-start
// txHost.tx is typed as Task
return this.txHost.tx.one(`SELECT * FROM user WHERE id = $1`);
// highlight-end
}

async createUser(name: string, email: string) {
return this.txHost.tx.none(
`INSERT INTO user (name, email) VALUES ($1, $2)`,
[name, email],
);
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Adapters for the following libraries are available:

- Prisma (see [@nestjs-cls/transactional-adapter-prisma](./01-prisma-adapter.md))
- Knex (see [@nestjs-cls/transactional-adapter-knex](./02-knex-adapter.md))
- pg-promise (see [@nestjs-cls/transactional-adapter-pg-promise](./03-pg-promise-adapter.md))

Adapters _will not_ be implemented for the following libraries:

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @nestjs-cls/transactional-adapter-pg-promise

`pg-promise` adapter for the `@nestjs-cls/transactional` plugin.

### ➡️ [Go to the documentation website](https://papooch.github.io/nestjs-cls/plugins/available-plugins/transactional) 📖
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module.exports = {
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: '.',
testRegex: '.*\\.spec\\.ts$',
transform: {
'^.+\\.ts$': 'ts-jest',
},
collectCoverageFrom: ['src/**/*.ts'],
coverageDirectory: '../coverage',
testEnvironment: 'node',
globals: {
'ts-jest': {
isolatedModules: true,
maxWorkers: 1,
},
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"name": "@nestjs-cls/transactional-adapter-pg-promise",
"version": "1.0.0",
"description": "A pg-promise adapter for @nestjs-cls/transactional",
"author": "Sam Artuso <samuele.a@gmail.com>",
"license": "MIT",
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Papooch/nestjs-cls.git"
},
"homepage": "https://papooch.github.io/nestjs-cls/",
"keywords": [
"nest",
"nestjs",
"cls",
"continuation-local-storage",
"als",
"AsyncLocalStorage",
"async_hooks",
"request context",
"async context"
],
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
"files": [
"dist/src/**/!(*.spec).d.ts",
"dist/src/**/!(*.spec).js"
],
"scripts": {
"prepack": "cp ../../../LICENSE ./LICENSE",
"prebuild": "rimraf dist",
"build": "tsc",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage"
},
"peerDependencies": {
"@nestjs-cls/transactional": "workspace:^1.0.1",
"nestjs-cls": "workspace:^4.0.1",
"pg-promise": "^11"
},
"devDependencies": {
"@nestjs/cli": "^10.0.2",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/jest": "^28.1.2",
"@types/node": "^18.0.0",
"jest": "^28.1.1",
"pg-promise": "^11",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5",
"ts-jest": "^28.0.5",
"ts-loader": "^9.3.0",
"ts-node": "^10.8.1",
"tsconfig-paths": "^4.0.0",
"typescript": "~4.8.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/transactional-adapter-pg-promise';
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { TransactionalAdapter } from '@nestjs-cls/transactional';
import { IDatabase } from 'pg-promise';

export type Database = IDatabase<unknown>;

type TxOptions = Parameters<Database['tx']>[0];

export interface PgPromiseTransactionalAdapterOptions {
/**
* The injection token for the pg-promise instance.
*/
dbInstanceToken: any;
}

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

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

optionsFactory = (pgPromiseDbInstance: Database) => ({
wrapWithTransaction: async (
options: TxOptions | null,
fn: (...args: any[]) => Promise<any>,
setClient: (client?: Database) => void,
) => {
return pgPromiseDbInstance.tx(options ?? {}, (tx) => {
setClient(tx as unknown as Database);
return fn();
});
},
getFallbackInstance: () => pgPromiseDbInstance,
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
db:
image: postgres:15
ports:
- 5444:5432
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
interval: 1s
timeout: 1s
retries: 5
Loading
Loading