Skip to content

Commit

Permalink
feat: add Knex transactional adapter (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
Papooch authored Jan 22, 2024
1 parent ae61d82 commit 53d4dd2
Show file tree
Hide file tree
Showing 13 changed files with 921 additions and 16 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Knex adapter

## Installation

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

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

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

```bash
yarn add @nestjs-cls/transactional-adapter-knex
```

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

```bash
pnpm add @nestjs-cls/transactional-adapter-knex
```

</TabItem>
</Tabs>

## Registration

```ts
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

```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');
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<TransactionalAdapterKnex>,
) {}

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

async createUser(name: string) {
return this.txHost
.tx('user')
.insert({ name: name, email: `${name}@email.com` })
.returning('*');
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ The plugin works in conjunction with various adapters that provide the actual tr

Adapters for the following libraries are available:

- Prisma (see [prisma-adapter](./01-prisma-adapter.md))
- Prisma (see [@nestjs-cls/transactional-adapter-prisma](./01-prisma-adapter.md))
- Knex (see [@nestjs-cls/transactional-adapter-knex](./02-knex-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 @@
test.db
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# @nestjs-cls/transactional-adapter-prisma

Pg (node-postgres) 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,67 @@
{
"name": "@nestjs-cls/transactional-adapter-knex",
"version": "1.0.0",
"description": "A Knex adapter for @nestjs-cls/transactional",
"author": "papooch",
"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",
"knex": "^3",
"nestjs-cls": "workspace:^4"
},
"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",
"knex": "^3.1.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5",
"sqlite3": "^5.1.7",
"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-knex';
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { TransactionalAdapter } from '@nestjs-cls/transactional';
import { Knex } from 'knex';

export interface KnexTransactionalAdapterOptions {
/**
* The injection token for the Knex instance.
*/
knexInstanceToken: any;
}

export class TransactionalAdapterKnex
implements TransactionalAdapter<Knex, Knex, Knex.TransactionConfig>
{
connectionToken: any;

constructor(options: KnexTransactionalAdapterOptions) {
this.connectionToken = options.knexInstanceToken;
}

optionsFactory = (knexInstance: Knex) => ({
wrapWithTransaction: async (
options: Knex.TransactionConfig,
fn: (...args: any[]) => Promise<any>,
setClient: (client?: Knex) => void,
) => {
return knexInstance.transaction((trx) => {
setClient(trx);
return fn();
}, options);
},
getFallbackInstance: () => knexInstance,
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
services:
db:
image: postgres:15
ports:
- 5432:5432
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres

Loading

0 comments on commit 53d4dd2

Please sign in to comment.