-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
373 additions
and
0 deletions.
There are no files selected for viewing
1 change: 1 addition & 0 deletions
1
packages/transactional-adapters/transactional-adapter-kysely/.gitignore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
test.db |
5 changes: 5 additions & 0 deletions
5
packages/transactional-adapters/transactional-adapter-kysely/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# @nestjs-cls/transactional-adapter-kysely | ||
|
||
Kysely adapter for the `@nestjs-cls/transactional` plugin. | ||
|
||
### ➡️ [Go to the documentation website](https://papooch.github.io/nestjs-cls/plugins/available-plugins/transactional/kysely-adapter) 📖 |
17 changes: 17 additions & 0 deletions
17
packages/transactional-adapters/transactional-adapter-kysely/jest.config.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}, | ||
}, | ||
}; |
72 changes: 72 additions & 0 deletions
72
packages/transactional-adapters/transactional-adapter-kysely/package.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
{ | ||
"name": "@nestjs-cls/transactional-adapter-kysely", | ||
"version": "1.0.0", | ||
"description": "A Kysely 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", | ||
"transaction", | ||
"transactional", | ||
"transactional decorator", | ||
"aop", | ||
"kysely" | ||
], | ||
"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:^2.0.0", | ||
"nestjs-cls": "workspace:^4.0.1", | ||
"kysely": "^0.27" | ||
}, | ||
"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", | ||
"better-sqlite3": "^9.3.0", | ||
"jest": "^28.1.1", | ||
"kysely": "^0.27.2", | ||
"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" | ||
} | ||
} |
1 change: 1 addition & 0 deletions
1
packages/transactional-adapters/transactional-adapter-kysely/src/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './lib/transactional-adapter-kysely'; |
33 changes: 33 additions & 0 deletions
33
...ansactional-adapters/transactional-adapter-kysely/src/lib/transactional-adapter-kysely.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}); | ||
} |
10 changes: 10 additions & 0 deletions
10
packages/transactional-adapters/transactional-adapter-kysely/test/docker-compose.yml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
181 changes: 181 additions & 0 deletions
181
...ansactional-adapters/transactional-adapter-kysely/test/transactional-adapter-knex.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
import { | ||
ClsPluginTransactional, | ||
Transactional, | ||
TransactionHost, | ||
} from '@nestjs-cls/transactional'; | ||
import { Inject, Injectable, Module } from '@nestjs/common'; | ||
import { Test, TestingModule } from '@nestjs/testing'; | ||
import { ClsModule } from 'nestjs-cls'; | ||
import Knex from 'knex'; | ||
import { TransactionalAdapterKnex } from '../src'; | ||
|
||
const KNEX = 'KNEX'; | ||
|
||
@Injectable() | ||
class UserRepository { | ||
constructor( | ||
private readonly txHost: TransactionHost<TransactionalAdapterKnex>, | ||
) {} | ||
|
||
async getUserById(id: number) { | ||
return this.txHost.tx('user').where({ id }).first(); | ||
} | ||
|
||
async createUser(name: string) { | ||
const created = await this.txHost | ||
.tx('user') | ||
.insert({ name: name, email: `${name}@email.com` }) | ||
.returning('*'); | ||
return created[0] ?? null; | ||
} | ||
} | ||
|
||
@Injectable() | ||
class UserService { | ||
constructor( | ||
private readonly userRepository: UserRepository, | ||
private readonly txHost: TransactionHost<TransactionalAdapterKnex>, | ||
@Inject(KNEX) | ||
private readonly knex: Knex.Knex, | ||
) {} | ||
|
||
@Transactional() | ||
async transactionWithDecorator() { | ||
const r1 = await this.userRepository.createUser('John'); | ||
const r2 = await this.userRepository.getUserById(r1.id); | ||
return { r1, r2 }; | ||
} | ||
|
||
@Transactional<TransactionalAdapterKnex>({ | ||
isolationLevel: 'serializable', | ||
}) | ||
async transactionWithDecoratorWithOptions() { | ||
const r1 = await this.userRepository.createUser('James'); | ||
const r2 = | ||
(await this.knex('user').where({ id: r1.id }).first()) ?? null; | ||
const r3 = await this.userRepository.getUserById(r1.id); | ||
return { r1, r2, r3 }; | ||
} | ||
|
||
async transactionWithFunctionWrapper() { | ||
return this.txHost.withTransaction( | ||
{ | ||
isolationLevel: 'serializable', | ||
}, | ||
async () => { | ||
const r1 = await this.userRepository.createUser('Joe'); | ||
const r2 = | ||
(await this.knex('user').where({ id: r1.id }).first()) ?? | ||
null; | ||
const r3 = await this.userRepository.getUserById(r1.id); | ||
return { r1, r2, r3 }; | ||
}, | ||
); | ||
} | ||
|
||
@Transactional() | ||
async transactionWithDecoratorError() { | ||
await this.userRepository.createUser('Nobody'); | ||
throw new Error('Rollback'); | ||
} | ||
} | ||
|
||
const knex = Knex({ | ||
client: 'sqlite', | ||
connection: { | ||
filename: 'test.db', | ||
}, | ||
useNullAsDefault: true, | ||
pool: { min: 1, max: 2 }, | ||
}); | ||
|
||
@Module({ | ||
providers: [ | ||
{ | ||
provide: KNEX, | ||
useValue: knex, | ||
}, | ||
], | ||
exports: [KNEX], | ||
}) | ||
class KnexModule {} | ||
|
||
@Module({ | ||
imports: [ | ||
KnexModule, | ||
ClsModule.forRoot({ | ||
plugins: [ | ||
new ClsPluginTransactional({ | ||
imports: [KnexModule], | ||
adapter: new TransactionalAdapterKnex({ | ||
knexInstanceToken: KNEX, | ||
}), | ||
}), | ||
], | ||
}), | ||
], | ||
providers: [UserService, UserRepository], | ||
}) | ||
class AppModule {} | ||
|
||
describe('Transactional', () => { | ||
let module: TestingModule; | ||
let callingService: UserService; | ||
|
||
beforeAll(async () => { | ||
await knex.schema.dropTableIfExists('user'); | ||
await knex.schema.createTable('user', (table) => { | ||
table.increments('id'); | ||
table.string('name'); | ||
table.string('email'); | ||
}); | ||
}); | ||
|
||
beforeEach(async () => { | ||
module = await Test.createTestingModule({ | ||
imports: [AppModule], | ||
}).compile(); | ||
await module.init(); | ||
callingService = module.get(UserService); | ||
}); | ||
|
||
afterAll(async () => { | ||
await knex.destroy(); | ||
}); | ||
|
||
describe('TransactionalAdapterKnex', () => { | ||
it('should run a transaction with the default options with a decorator', async () => { | ||
const { r1, r2 } = await callingService.transactionWithDecorator(); | ||
expect(r1).toEqual(r2); | ||
const users = await knex('user'); | ||
expect(users).toEqual(expect.arrayContaining([r1])); | ||
}); | ||
|
||
it('should run a transaction with the specified options with a decorator', async () => { | ||
const { r1, r2, r3 } = | ||
await callingService.transactionWithDecoratorWithOptions(); | ||
expect(r1).toEqual(r3); | ||
expect(r2).toBeNull(); | ||
const users = await knex('user'); | ||
expect(users).toEqual(expect.arrayContaining([r1])); | ||
}); | ||
it('should run a transaction with the specified options with a function wrapper', async () => { | ||
const { r1, r2, r3 } = | ||
await callingService.transactionWithFunctionWrapper(); | ||
expect(r1).toEqual(r3); | ||
expect(r2).toBeNull(); | ||
const users = await knex('user'); | ||
expect(users).toEqual(expect.arrayContaining([r1])); | ||
}); | ||
|
||
it('should rollback a transaction on error', async () => { | ||
await expect( | ||
callingService.transactionWithDecoratorError(), | ||
).rejects.toThrow(new Error('Rollback')); | ||
const users = await knex('user'); | ||
expect(users).toEqual( | ||
expect.not.arrayContaining([{ name: 'Nobody' }]), | ||
); | ||
}); | ||
}); | ||
}); |
8 changes: 8 additions & 0 deletions
8
packages/transactional-adapters/transactional-adapter-kysely/tsconfig.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"extends": "../../../tsconfig.json", | ||
"compilerOptions": { | ||
"outDir": "dist", | ||
"rootDir": "." | ||
}, | ||
"include": ["src/**/*.ts", "test/**/*.ts"] | ||
} |
Oops, something went wrong.