Skip to content

feat(transactional-adapter-drizzle-orm): add drizzle orm adapter #180

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

Merged
merged 4 commits into from
Oct 27, 2024
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,151 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Drizzle ORM adapter

## Installation

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

```bash
npm install @nestjs-cls/transactional-adapter-drizzle-orm
```

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

```bash
yarn add @nestjs-cls/transactional-adapter-drizzle-orm
```

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

```bash
pnpm add @nestjs-cls/transactional-adapter-drizzle-orm
```

</TabItem>
</Tabs>

## Registration

```ts
ClsModule.forRoot({
plugins: [
new ClsPluginTransactional({
imports: [
// module in which Drizzle is provided
DrizzleModule
],
adapter: new TransactionalAdapterDrizzleOrm({
// the injection token of the Drizzle client instance
drizzleInstanceToken: DRIZZLE,
}),
}),
],
}),
```

## Typing & usage

In Drizzle, the client type is inferred from the database type [_depending on the database driver_](https://orm.drizzle.team/docs/connect-overview).

For the typing to work properly, you need to provide the client type as the type parameter for the `TransactionalAdapterDrizzleOrm` when injecting it.

For example, if you create a client like this:

```ts
const drizzleClient = drizzle('<connection string>'{
schema: {
users,
},
});
```

Then create a custom adapter type based on the client type:

```ts
type MyDrizzleAdapter = TransactionAdapterDrizzleOrm<typeof drizzleClient>;
```

And use it as a type parameter for `TransactionHost` when injecting it:

```ts
constructor(
private readonly txHost: TransactionHost<MyDrizzleAdapter>,
) {}
```

## Example

This example assumes usage with Postgres together with `pg` and `drizzle-orm/pg-core`

```ts title="database.ts"
const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text().notNull(),
email: text().notNull(),
});

const drizzleClient = drizzle(
new Pool({
connectionString: '<connection string>',
max: 2,
}),
{
schema: {
users,
},
},
);

type DrizzleClient = typeof drizzleClient;
type MyDrizzleAdapter = TransactionAdapterDrizzleOrm<DrizzleClient>;
```

```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(user.id);
// highlight-end
assert(foundUser.id === user.id);
}
}
```

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

async getUserById(id: number) {
// highlight-start
// txHost.tx is typed as DrizzleClient
return this.tx.query.users.findFirst({
where: eq(users.id, id),
});
// highlight-end
}

async createUser(name: string) {
const created = await this.tx
.insert(users)
.values({
name: name,
email: `${name}@email.com`,
})
.returning()
.execute();
return created[0];
}
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ Adapters for the following libraries are available:
- TypeORM (see [@nestjs-cls/transactional-adapter-typeorm](./05-typeorm-adapter.md))
- MongoDB (see [@nestjs-cls/transactional-adapter-mongodb](./06-mongodb-adapter.md))
- MongoDB (see [@nestjs-cls/transactional-adapter-mongoose](./07-mongoose-adapter.md))
- Drizzle ORM (see [@nestjs-cls/transactional-adapter-drizzle-orm](./08-drizzle-orm-adapter.md))

Adapters _will not_ be implemented for the following libraries (unless there is a serious demand):

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

Drizzle ORM adapter for the `@nestjs-cls/transactional` plugin.

### ➡️ [Go to the documentation website](https://papooch.github.io/nestjs-cls/plugins/available-plugins/transactional/knex-adapter) 📖
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',
{
isolatedModules: true,
maxWorkers: 1,
},
],
},
collectCoverageFrom: ['src/**/*.ts'],
coverageDirectory: '../coverage',
testEnvironment: 'node',
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
{
"name": "@nestjs-cls/transactional-adapter-drizzle-orm",
"version": "1.0.0",
"description": "A Drizzle ORM 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",
"drizzle-orm",
"drizzle"
],
"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.4.2",
"drizzle-orm": "^0",
"nestjs-cls": "workspace:^4.4.1"
},
"devDependencies": {
"@nestjs/cli": "^10.0.2",
"@nestjs/common": "^10.3.7",
"@nestjs/core": "^10.3.7",
"@nestjs/testing": "^10.3.7",
"@types/jest": "^28.1.2",
"@types/node": "^18.0.0",
"@types/pg": "^8",
"drizzle-orm": "^0.34.1",
"jest": "^29.7.0",
"pg": "^8.11.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5",
"ts-jest": "^29.1.2",
"ts-loader": "^9.3.0",
"ts-node": "^10.8.1",
"tsconfig-paths": "^4.0.0",
"typescript": "5.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/transactional-adapter-drizzle-orm';
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { TransactionalAdapter } from '@nestjs-cls/transactional';

type AnyDrizzleClient = {
transaction: (
fn: (tx: AnyDrizzleClient) => Promise<any>,
options?: any,
) => Promise<any>;
};

type DrizzleTransactionOptions<T> = T extends AnyDrizzleClient
? Parameters<T['transaction']>[1]
: never;

export interface DrizzleOrmTransactionalAdapterOptions<
TClient extends AnyDrizzleClient,
> {
/**
* The injection token for the Drizzle instance.
*/
drizzleInstanceToken: any;

/**
* Default options for the transaction. These will be merged with any transaction-specific options
* passed to the `@Transactional` decorator or the `TransactionHost#withTransaction` method.
*/
defaultTxOptions?: Partial<DrizzleTransactionOptions<TClient>>;
}

export class TransactionalAdapterDrizzleOrm<TClient extends AnyDrizzleClient>
implements
TransactionalAdapter<
TClient,
TClient,
DrizzleTransactionOptions<TClient>
>
{
connectionToken: any;

defaultTxOptions?: Partial<DrizzleTransactionOptions<TClient>>;

constructor(options: DrizzleOrmTransactionalAdapterOptions<TClient>) {
this.connectionToken = options.drizzleInstanceToken;
this.defaultTxOptions = options.defaultTxOptions;
}

optionsFactory = (drizzleInstance: TClient) => ({
wrapWithTransaction: async (
options: DrizzleTransactionOptions<TClient>,
fn: (...args: any[]) => Promise<any>,
setClient: (client?: TClient) => void,
) => {
return drizzleInstance.transaction(async (tx) => {
setClient(tx as TClient);
return fn();
}, options);
},
getFallbackInstance: () => drizzleInstance,
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
drizzle-orm-test-db:
image: postgres:15
ports:
- 5447: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