Skip to content
Open
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
Expand Up @@ -4,8 +4,11 @@ type AnyDrizzleClient = {
transaction: (fn: (tx: AnyDrizzleClient) => any, options?: any) => any;
};

// The options of `transaction()` are optional, so drop the `undefined`: under
// `exactOptionalPropertyTypes` it stops the adapter from matching
// `TransactionalAdapter`, which types `TransactionHost#tx` as `never`.
type DrizzleTransactionOptions<T> = T extends AnyDrizzleClient
? Parameters<T['transaction']>[1]
? NonNullable<Parameters<T['transaction']>[1]>
: never;

export interface DrizzleOrmTransactionalAdapterOptions<
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';

const testDir = dirname(fileURLToPath(import.meta.url));

/**
* Type-checks `source` the way a consumer's project would: as a file in this
* package's `test` folder that imports the packages by name, so it sees their
* built declarations (`yarn build` has to run first). Returns its errors.
*/
function typeCheck(source: string, options: ts.CompilerOptions) {
const fileName = resolve(testDir, '__type-check__.ts');
const compilerOptions: ts.CompilerOptions = {
strict: true,
noEmit: true,
skipLibCheck: true,
target: ts.ScriptTarget.ES2021,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.Node10,
esModuleInterop: true,
...options,
};
const host = ts.createCompilerHost(compilerOptions);
const { getSourceFile, fileExists, readFile } = host;
host.fileExists = (f) => f === fileName || fileExists.call(host, f);
host.readFile = (f) => (f === fileName ? source : readFile.call(host, f));
host.getSourceFile = (f, ...rest) =>
f === fileName
? ts.createSourceFile(f, source, ts.ScriptTarget.ES2021)
: getSourceFile.call(host, f, ...rest);
const program = ts.createProgram([fileName], compilerOptions, host);
return ts
.getPreEmitDiagnostics(program, program.getSourceFile(fileName))
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
}

const source = `
import { TransactionHost } from '@nestjs-cls/transactional';
import { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { TransactionalAdapterDrizzleOrm } from '@nestjs-cls/transactional-adapter-drizzle-orm';

new TransactionalAdapterDrizzleOrm<NodePgDatabase>({
drizzleInstanceToken: 'DRIZZLE',
defaultTxOptions: { isolationLevel: 'serializable' },
});

declare const txHost: TransactionHost<
TransactionalAdapterDrizzleOrm<NodePgDatabase>
>;
txHost.tx.select();
txHost.withTransaction({ accessMode: 'read only' }, async () => {
txHost.tx.select();
});
`;

describe('TransactionalAdapterDrizzleOrm types', () => {
it.each([false, true])(
'types TransactionHost#tx as the Drizzle client (exactOptionalPropertyTypes: %s)',
(exactOptionalPropertyTypes) => {
expect(typeCheck(source, { exactOptionalPropertyTypes })).toEqual(
[],
);
},
);
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { TransactionalAdapter } from '@nestjs-cls/transactional';
import { ClientSession, Connection } from 'mongoose';

type MongooseTransactionOptions = Parameters<Connection['transaction']>[1];
// The options of `transaction()` are optional, so drop the `undefined`: under
// `exactOptionalPropertyTypes` it stops the adapter from matching
// `TransactionalAdapter`, which types `TransactionHost#tx` as `never`.
type MongooseTransactionOptions = NonNullable<
Parameters<Connection['transaction']>[1]
>;

export interface MongoDBTransactionalAdapterOptions {
/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';

const testDir = dirname(fileURLToPath(import.meta.url));

/**
* Type-checks `source` the way a consumer's project would: as a file in this
* package's `test` folder that imports the packages by name, so it sees their
* built declarations (`yarn build` has to run first). Returns its errors.
*/
function typeCheck(source: string, options: ts.CompilerOptions) {
const fileName = resolve(testDir, '__type-check__.ts');
const compilerOptions: ts.CompilerOptions = {
strict: true,
noEmit: true,
skipLibCheck: true,
target: ts.ScriptTarget.ES2021,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.Node10,
esModuleInterop: true,
...options,
};
const host = ts.createCompilerHost(compilerOptions);
const { getSourceFile, fileExists, readFile } = host;
host.fileExists = (f) => f === fileName || fileExists.call(host, f);
host.readFile = (f) => (f === fileName ? source : readFile.call(host, f));
host.getSourceFile = (f, ...rest) =>
f === fileName
? ts.createSourceFile(f, source, ts.ScriptTarget.ES2021)
: getSourceFile.call(host, f, ...rest);
const program = ts.createProgram([fileName], compilerOptions, host);
return ts
.getPreEmitDiagnostics(program, program.getSourceFile(fileName))
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
}

const source = `
import { TransactionHost } from '@nestjs-cls/transactional';
import { TransactionalAdapterMongoose } from '@nestjs-cls/transactional-adapter-mongoose';

new TransactionalAdapterMongoose({
mongooseConnectionToken: 'CONNECTION',
defaultTxOptions: { readPreference: 'primary' },
});

declare const txHost: TransactionHost<TransactionalAdapterMongoose>;
txHost.tx?.inTransaction();
txHost.withTransaction({ maxCommitTimeMS: 1000 }, async () => {
txHost.tx?.inTransaction();
});
`;

describe('TransactionalAdapterMongoose types', () => {
it.each([false, true])(
'types TransactionHost#tx as the session (exactOptionalPropertyTypes: %s)',
(exactOptionalPropertyTypes) => {
expect(typeCheck(source, { exactOptionalPropertyTypes })).toEqual(
[],
);
},
);
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { TransactionalAdapter } from '@nestjs-cls/transactional';
import {
TransactionalAdapter,
TransactionalAdapterOptions,
} from '@nestjs-cls/transactional';
import { PrismaClient } from '@prisma/client';
import { getSavepointStatements, SQLFlavor } from './savepoint-syntax.js';
import { randomUUID } from 'crypto';
Expand All @@ -11,9 +14,12 @@ export type PrismaTransactionalClient<
TClient extends AnyTransactionClient = PrismaClient,
> = Parameters<Parameters<TClient['$transaction']>[0]>[0];

// The options of `$transaction()` are optional, so drop the `undefined`: under
// `exactOptionalPropertyTypes` it stops the adapter from matching
// `TransactionalAdapter`, which types `TransactionHost#tx` as `never`.
export type PrismaTransactionOptions<
TClient extends AnyTransactionClient = PrismaClient,
> = Parameters<TClient['$transaction']>[1];
> = NonNullable<Parameters<TClient['$transaction']>[1]>;

export interface PrismaTransactionalAdapterOptions<
TClient extends AnyTransactionClient = PrismaClient,
Expand Down Expand Up @@ -59,7 +65,15 @@ export class TransactionalAdapterPrisma<
this.sqlFlavor = options.sqlFlavor;
}

optionsFactory = (prisma: TClient) => ({
// The return type is spelled out so that the emitted declaration matches
// `TransactionalAdapter`, which an inferred `wrapWithNestedTransaction`
// of type `... | undefined` does not under `exactOptionalPropertyTypes`.
optionsFactory = (
prisma: TClient,
): TransactionalAdapterOptions<
PrismaTransactionalClient<TClient>,
PrismaTransactionOptions<TClient>
> => ({
wrapWithTransaction: async (
options: PrismaTransactionOptions,
fn: (...args: any[]) => Promise<any>,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';

const testDir = dirname(fileURLToPath(import.meta.url));

/**
* Type-checks `source` the way a consumer's project would: as a file in this
* package's `test` folder that imports the packages by name, so it sees their
* built declarations (`yarn build` has to run first). Returns its errors.
*/
function typeCheck(source: string, options: ts.CompilerOptions) {
const fileName = resolve(testDir, '__type-check__.ts');
const compilerOptions: ts.CompilerOptions = {
strict: true,
noEmit: true,
skipLibCheck: true,
target: ts.ScriptTarget.ES2021,
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.Node10,
esModuleInterop: true,
...options,
};
const host = ts.createCompilerHost(compilerOptions);
const { getSourceFile, fileExists, readFile } = host;
host.fileExists = (f) => f === fileName || fileExists.call(host, f);
host.readFile = (f) => (f === fileName ? source : readFile.call(host, f));
host.getSourceFile = (f, ...rest) =>
f === fileName
? ts.createSourceFile(f, source, ts.ScriptTarget.ES2021)
: getSourceFile.call(host, f, ...rest);
const program = ts.createProgram([fileName], compilerOptions, host);
return ts
.getPreEmitDiagnostics(program, program.getSourceFile(fileName))
.map((d) => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
}

const source = `
import { TransactionHost } from '@nestjs-cls/transactional';
import { PrismaClient } from '@prisma/client';
import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma';

new TransactionalAdapterPrisma<PrismaClient>({
prismaInjectionToken: PrismaClient,
defaultTxOptions: { timeout: 1000 },
});

declare const txHost: TransactionHost<TransactionalAdapterPrisma<PrismaClient>>;
txHost.tx.$queryRaw\`SELECT 1\`;
txHost.withTransaction({ maxWait: 1000 }, async () => {
txHost.tx.$queryRaw\`SELECT 1\`;
});
`;

describe('TransactionalAdapterPrisma types', () => {
it.each([false, true])(
'types TransactionHost#tx as the Prisma client (exactOptionalPropertyTypes: %s)',
(exactOptionalPropertyTypes) => {
expect(typeCheck(source, { exactOptionalPropertyTypes })).toEqual(
[],
);
},
);
});