### Knex Transaction Handling Example Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/99-creating-custom-adapter.md Demonstrates how to initiate and manage transactions using the Knex library. It shows starting a transaction, performing operations within it using a transaction object, and executing queries outside the transactional context. ```typescript import { Knex } from 'knex'; const knex = Knex({ // [...] knex init settings }); async function main() { // highlight-start // Knex uses the transaction method on the `knex` instance to start a new transaction. // highlight-end await knex.transaction( // highlight-start // The first parameter to the method is a callback that receives a `tx` object. // highlight-end async (tx) => { // highlight-start // Within the callback, the `tx` object refers to the same transaction instance. // This is what we'll need to store in the CLS context. // highlight-end await tx('users').insert({ name: 'John' }); await tx('users').insert({ name: 'Jane' }); }, // highlight-start // And the second parameter is the transaction options. // highlight-end { isolationLevel: 'serializable' }, ); // highlight-start // The `knex` instance itself can be used to issue queries outside of // the transactional context. This is what we'll provide as the fallback. // highlight-end const users = await knex('users') .where({ name: 'John' }) .orWhere({ name: 'Jane' }); } ``` -------------------------------- ### Install Prisma Adapter (yarn) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/01-prisma-adapter.md Install the Prisma adapter package using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-prisma ``` -------------------------------- ### Install Prisma Adapter (npm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/01-prisma-adapter.md Install the Prisma adapter package using npm. ```bash npm install @nestjs-cls/transactional-adapter-prisma ``` -------------------------------- ### Install pg-promise Adapter (yarn) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/04-pg-promise-adapter.md Install the pg-promise transactional adapter using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-pg-promise ``` -------------------------------- ### Install Prisma Adapter (pnpm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/01-prisma-adapter.md Install the Prisma adapter package using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-prisma ``` -------------------------------- ### Install pg-promise Adapter (pnpm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/04-pg-promise-adapter.md Install the pg-promise transactional adapter using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-pg-promise ``` -------------------------------- ### Install pg-promise Adapter (npm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/04-pg-promise-adapter.md Install the pg-promise transactional adapter using npm. ```bash npm install @nestjs-cls/transactional-adapter-pg-promise ``` -------------------------------- ### Install Mongoose adapter with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/07-mongoose-adapter.md Use this command to install the Mongoose adapter using npm. ```bash npm install @nestjs-cls/transactional-adapter-mongoose ``` -------------------------------- ### Install nestjs-cls with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/01_installation.md Use this command to install the package using yarn. Ensure you have @nestjs/core and @nestjs/common installed as peer dependencies. ```sh yarn add nestjs-cls ``` -------------------------------- ### Install Mongoose adapter with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/07-mongoose-adapter.md Use this command to install the Mongoose adapter using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-mongoose ``` -------------------------------- ### Start Local Development Server Source: https://github.com/papooch/nestjs-cls/blob/main/docs/README.md Starts a local development server. Changes are reflected live without server restart. ```bash yarn start ``` -------------------------------- ### Install nestjs-cls with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/01_installation.md Use this command to install the package using pnpm. Ensure you have @nestjs/core and @nestjs/common installed as peer dependencies. ```sh pnpm add nestjs-cls ``` -------------------------------- ### Install Mongoose adapter with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/07-mongoose-adapter.md Use this command to install the Mongoose adapter using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-mongoose ``` -------------------------------- ### Install nestjs-cls with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/01_installation.md Use this command to install the package using npm. Ensure you have @nestjs/core and @nestjs/common installed as peer dependencies. ```sh npm install nestjs-cls ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/papooch/nestjs-cls/blob/main/docs/README.md Run this command to install project dependencies using Yarn. ```bash yarn ``` -------------------------------- ### Install @nestjs-cls/transactional with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md Use this command to install the transactional plugin using yarn. ```bash yarn add @nestjs-cls/transactional ``` -------------------------------- ### Install @nestjs-cls/transactional with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md Use this command to install the transactional plugin using pnpm. ```bash pnpm add @nestjs-cls/transactional ``` -------------------------------- ### Install Drizzle ORM Adapter (pnpm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/08-drizzle-orm-adapter.md Install the Drizzle ORM adapter package using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-drizzle-orm ``` -------------------------------- ### Install Drizzle ORM Adapter (yarn) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/08-drizzle-orm-adapter.md Install the Drizzle ORM adapter package using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-drizzle-orm ``` -------------------------------- ### Install Kysely Adapter with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/03-kysely-adapter.md Use this command to install the Kysely adapter package using npm. ```bash npm install @nestjs-cls/transactional-adapter-kysely ``` -------------------------------- ### Install Kysely Adapter with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/03-kysely-adapter.md Use this command to install the Kysely adapter package using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-kysely ``` -------------------------------- ### Install @nestjs-cls/transactional with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md Use this command to install the transactional plugin using npm. ```bash npm install @nestjs-cls/transactional ``` -------------------------------- ### Install Drizzle ORM Adapter (npm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/08-drizzle-orm-adapter.md Install the Drizzle ORM adapter package using npm. ```bash npm install @nestjs-cls/transactional-adapter-drizzle-orm ``` -------------------------------- ### Install Kysely Adapter with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/03-kysely-adapter.md Use this command to install the Kysely adapter package using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-kysely ``` -------------------------------- ### Install MongoDB Transactional Adapter (npm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/06-mongodb-adapter.md Use npm to install the MongoDB transactional adapter for NestJS-CLS. ```bash npm install @nestjs-cls/transactional-adapter-mongodb ``` -------------------------------- ### Install MongoDB Transactional Adapter (yarn) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/06-mongodb-adapter.md Use yarn to install the MongoDB transactional adapter for NestJS-CLS. ```bash yarn add @nestjs-cls/transactional-adapter-mongodb ``` -------------------------------- ### Context Setup with `@UseCls()` Decorator Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/03_features-and-use-cases/06_proxy-providers.md Use the `@UseCls()` decorator to automatically wrap a function with `cls.run()`. The `setup` function within the decorator prepares the context, and proxy providers are resolved automatically after this phase. ```typescript @Injectable() export class CronController { constructor(private readonly someService: SomeService); @Cron('45 * * * * *') @UseCls({ // highlight-start setup: (cls) => { cls.set('some-key', 'some-value'); }, // highlight-end }) async handleCron() { await this.someService.doTheThing(); } } ``` -------------------------------- ### Install MongoDB Transactional Adapter (pnpm) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/06-mongodb-adapter.md Use pnpm to install the MongoDB transactional adapter for NestJS-CLS. ```bash pnpm add @nestjs-cls/transactional-adapter-mongodb ``` -------------------------------- ### Automatically Mount ClsGuard Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/02_setting-up-cls-context/02_using-a-guard.md Configure ClsModule.forRoot() with `guard: { mount: true }` to automatically set up the CLS context when the application starts. ```typescript import { ClsModule } from 'nestjs-cls'; import { Module } from '@nestjs/common'; @Module({ imports: [ ClsModule.forRoot({ // highlight-start guard: { mount: true }, // highlight-end }), ], // ... }) export class AppModule {} ``` -------------------------------- ### Install TypeORM Transactional Adapter with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md Use this command to install the TypeORM transactional adapter for NestJS-CLS using yarn. ```bash yarn add @nestjs-cls/transactional-adapter-typeorm ``` -------------------------------- ### Install TypeORM Transactional Adapter with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md Use this command to install the TypeORM transactional adapter for NestJS-CLS using npm. ```bash npm install @nestjs-cls/transactional-adapter-typeorm ``` -------------------------------- ### Install TypeORM Transactional Adapter with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md Use this command to install the TypeORM transactional adapter for NestJS-CLS using pnpm. ```bash pnpm add @nestjs-cls/transactional-adapter-typeorm ``` -------------------------------- ### Install Knex Adapter with npm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/02-knex-adapter.md Install the Knex adapter for NestJS CLS using npm. This package provides transactional capabilities for Knex.js. ```bash npm install @nestjs-cls/transactional-adapter-knex ``` -------------------------------- ### Install Knex Adapter with pnpm Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/02-knex-adapter.md Install the Knex adapter for NestJS CLS using pnpm. This package provides transactional capabilities for Knex.js. ```bash pnpm add @nestjs-cls/transactional-adapter-knex ``` -------------------------------- ### Registering Plugins with forRootAsync Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/index.md For asynchronous module setup, pass instantiated plugins to the `plugins` array in `ClsModule.forRootAsync()`. ```typescript ClsModule.forRootAsync({ // highlight-start plugins: [new MyPlugin()], // highlight-end }); ``` -------------------------------- ### Install Knex Adapter with yarn Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/02-knex-adapter.md Install the Knex adapter for NestJS CLS using yarn. This package provides transactional capabilities for Knex.js. ```bash yarn add @nestjs-cls/transactional-adapter-knex ``` -------------------------------- ### Transactional Repository Example Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/01-prisma-adapter.md Example of a repository class utilizing TransactionHost to access the transactional PrismaClient instance for database operations within a transaction. ```typescript @Injectable() class UserRepository { constructor( private readonly txHost: TransactionHost, ) {} async getUserById(id: number) { // highlight-start // txHost.tx is typed as the transactional PrismaClient return this.txHost.tx.user.findUnique({ where: { id } }); // highlight-end } async createUser(name: string) { return this.txHost.tx.user.create({ data: { name: name, email: `${name}@email.com` }, }); } } ``` -------------------------------- ### Transactional Repository Example Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md Example of a repository class using TransactionHost to access the transactional EntityManager (txHost.tx) for database operations within a transaction. ```typescript @Injectable() class UserRepository { constructor( private readonly txHost: TransactionHost, ) {} async getUserById(id: number) { // highlight-start // txHost.tx is typed as EntityManager return await this.txHost.tx.getRepository(User).findOneBy({ id }); // highlight-end } async createUser(name: string, email: string) { return await this.txHost.tx.getRepository(User).save({ name, email: `${name}@email.com`, }); } } ``` -------------------------------- ### Example Usage in a Service Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/03_features-and-use-cases/01_request-id.md Demonstrates how calling a method within a CLS context (e.g., in `MyService`) will correctly retrieve the request ID when using the custom logger. ```typescript @Injectable() class MyService { constructor(private readonly logger: MyLogger); hello() { this.logger.log('Hello'); // -> logs for ex.: "<44c2d8ff-49a6-4244-869f-75a2df11517a> Hello" } } ``` -------------------------------- ### Drizzle ORM Setup with Postgres Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/08-drizzle-orm-adapter.md Sets up the Drizzle client for use with Postgres, including schema definition and connection pooling. This configuration is necessary before using the Drizzle ORM adapter. ```typescript const users = pgTable('users', { id: serial('id').primaryKey(), name: text().notNull(), email: text().notNull(), }); const drizzleClient = drizzle( new Pool({ connectionString: '', max: 2, }), { schema: { users, }, }, ); type DrizzleClient = typeof drizzleClient; type MyDrizzleAdapter = TransactionAdapterDrizzleOrm; ``` -------------------------------- ### Setup CLS in Middleware Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/03_features-and-use-cases/02_additional-cls-setup.md Configure the CLS middleware to set custom values like 'TENANT_ID' and 'AUTH' from the request object. ```typescript ClsModule.forRoot({ middleware: { mount: true, setup: (cls, req: Request, res: Response) => { cls.set('TENANT_ID', req.params['tenantId']); cls.set('AUTH', { authenticated: false }); }, }, }); ``` -------------------------------- ### Customize Plugin with Constructor Options Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/02_plugin-api.md Extend the plugin to accept constructor options, allowing customization of the property name from which the user is retrieved from the request. This example shows how to use a dynamic property name in the `afterSetup` hook. ```typescript export class UserPlugin extends ClsPluginBase { constructor(userPropertyName: string) { super('user-plugin'); // [...] afterSetup(cls, context) { switch (context.kind) { case 'middleware': cls.set(USER_CLS_SYMBOL, context.req[userPropertyName]); break; ``` -------------------------------- ### User Service Transaction Example Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/06-mongodb-adapter.md Demonstrates how to use the @Transactional() decorator in a service to ensure that multiple repository operations are executed within a single database transaction. ```typescript @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); } } ``` -------------------------------- ### Install Dev Dependency in Workspace Source: https://github.com/papooch/nestjs-cls/blob/main/CONTRIBUTING.md Use this command to add a development dependency to a specific package within the monorepo. Ensure you replace `` with the actual package identifier. ```bash yarn workspace @nestjs-cls/transactional-adapter-prisma add -D sqlite3 ``` -------------------------------- ### Mock TransactionHost Provider Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md If TransactionHost is needed in tests, mock it as a regular provider. This example shows how to provide a mock implementation for TransactionHost with a mock `tx` object containing a `query` function. ```typescript const transactionHostMock = { tx: { query: jest.fn() }, }; const module = Test.createTestingModule({ providers: [ ServiceUnderTest, // highlight-start { // Provide the mock of the TransactionHost provide: TransactionHost, useValue: transactionHostMock, }, // highlight-end ], }); ``` -------------------------------- ### Initialize CLS Context with cls.run() Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/03_how-it-works.md This is the primary method to set up the CLS context. Anything called within the same callback chain will have access to the CLS storage. ```javascript cls.run(() => { // Code that needs CLS access }); ``` -------------------------------- ### ClsModule.forRoot() and ClsModule.forRootAsync() Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/04_api/02_module-options.md Configuration options for the root CLS module. ```APIDOC ## ClsModule.forRoot() and ClsModule.forRootAsync() ### Description Configures the root CLS module with various options for middleware, guards, interceptors, global scope, proxy providers, and plugins. ### Method `static forRoot(options: ClsModuleOptions): DynamicModule` `static forRootAsync(options: ClsModuleOptionsAsync): DynamicModule` ### Parameters #### Request Body - **middleware** (ClsMiddlewareOptions) - Optional - Options for `ClsMiddleware`. - **guard** (ClsGuardOptions) - Optional - Options for `ClsGuard`. - **interceptor** (ClsInterceptorOptions) - Optional - Options for `ClsInterceptor`. - **global** (boolean) - Optional (default: `false`) - Makes the module global. - **proxyProviders** (Type[]) - Optional - Array of synchronous Proxy Providers for the root module. - **plugins** (ClsPlugin[]) - Optional - Array of registered plugins. `forRootAsync` also accepts `imports`, `inject`, and `useFactory`. ### Request Example ```json { "middleware": { "mountPath": "/cls", "generateId": true }, "global": true, "plugins": [] } ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an endpoint) #### Response Example N/A ``` -------------------------------- ### Initialize CLS Context with cls.enter() Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/03_how-it-works.md An alternative to `cls.run()`. Use this if you need more manual control over entering and exiting the CLS context. Refer to security considerations for details. ```javascript cls.enter(); // Code that needs CLS access cls.exit(); ``` -------------------------------- ### Deploy Website using SSH Source: https://github.com/papooch/nestjs-cls/blob/main/docs/README.md Builds the website and pushes it to the 'gh-pages' branch using SSH. Requires setting the USE_SSH environment variable. ```bash USE_SSH=true yarn deploy ``` -------------------------------- ### ClsContextOptions Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/04_api/01_service-interface.md Configuration options for nested CLS context creation. ```APIDOC ## ClsContextOptions ### Description Options object that can be passed to `run` and `enter` methods to configure nested CLS context behavior. ### Properties - **`ifNested?: 'inherit' | 'reuse' | 'override'`** Determines the behavior when a nested CLS context is created within an existing one. Has no effect if no parent context exists. - `inherit` (default): Runs the callback with a shallow copy of the parent context. Modifications to top-level properties are not reflected in the parent, but modifications to existing properties are. - `reuse`: Reuses the existing parent context. All modifications will be reflected in the parent context. - `override`: Runs the callback with a new, empty context. No values from the parent context are accessible. ``` -------------------------------- ### Build Static Website Content Source: https://github.com/papooch/nestjs-cls/blob/main/docs/README.md Generates static content for the website into the 'build' directory, ready for hosting. ```bash yarn build ``` -------------------------------- ### Registering Plugins with forRoot Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/index.md Use the `plugins` option within `ClsModule.forRoot()` to enable pre-built integrations. Ensure `MyPlugin` is correctly instantiated. ```typescript ClsModule.forRoot({ // highlight-start plugins: [new MyPlugin()], // highlight-end }); ``` -------------------------------- ### Create User and Account with TransactionHost Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md Use TransactionHost to ensure that creating a user and their associated account are atomic operations. If either fails, the entire transaction is rolled back. ```typescript import { TransactionHost } from '@nestjs-cls/transactional'; import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma'; // ... other imports @Injectable() class UserService { constructor( // highlight-start private readonly txHost: TransactionHost, // highlight-end private readonly accountService: AccountService, ) {} async createUser(name: string): Promise { return this.txHost.withTransaction(async () => { const user = await this.txHost.tx.user.create({ data: { name } }); await this.accountService.createAccountForUser(user.id); return user; }); } } ``` ```typescript import { TransactionHost } from '@nestjs-cls/transactional'; import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma'; // ... other imports @Injectable() class AccountService { constructor( private readonly txHost: TransactionHost, ) {} async createAccountForUser(id: number): Promise { return this.txHost.tx.user.create({ data: { userId: id, number: Math.random() }, }); } } ``` -------------------------------- ### ClsModule.forFeature() and ClsModule.forFeatureAsync() Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/04_api/02_module-options.md Configures feature modules for registering Proxy Providers. ```APIDOC ## ClsModule.forFeature() and ClsModule.forFeatureAsync() ### Description Registers Proxy Providers for feature modules. The sync method accepts Class Proxy providers, while the async method accepts options for class or factory providers. ### Method `static forFeature(options: ClsModuleProxyClassProviderOptions | ClsModuleProxyFactoryProviderOptions): DynamicModule` `static forFeatureAsync(options: ClsModuleProxyClassProviderOptionsAsync | ClsModuleProxyFactoryProviderOptionsAsync): DynamicModule` ### Parameters #### Request Body - **provide** (any) - Optional - Custom injection token for the provider. - **imports** (any[]) - Optional - Imported modules required for the provider. - **extraProviders** (Provider[]) - Optional - Additional providers for the Proxy. - **useClass** (Type) - Required for `ClsModuleProxyClassProviderOptions` - The target class decorated with `@InjectableProxy`. - **inject** (any[]) - Required for `ClsModuleProxyFactoryProviderOptions` - Injection tokens for the `useFactory` providers. - **useFactory** (...args: any[]) => any - Required for `ClsModuleProxyFactoryProviderOptions` - Factory function to create the Proxy Provider. - **type** ('function' | 'object') - Optional (default: `'object'`) - Type of the Proxy Provider. - **strict** (boolean) - Optional (default: `false`) - Whether to register in strict mode. ### Request Example ```json // Using useClass { "useClass": "MyProxyClass", "extraProviders": [] } // Using useFactory { "inject": ["SomeService"], "useFactory": "(someService) => new MyProxyClass(someService)", "type": "object" } ``` ### Response #### Success Response (200) N/A (This is a configuration method, not an endpoint) #### Response Example N/A ``` -------------------------------- ### Transactional Service Example Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md Example of a service method decorated with @Transactional() that executes multiple repository operations within a single transaction. The tx property on TransactionHost is typed as EntityManager. ```typescript @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); } } ``` -------------------------------- ### Manually Mount ClsMiddleware in Bootstrap Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/02_setting-up-cls-context/01_using-a-middleware.md Mount ClsMiddleware directly in the bootstrap method using `app.use()` when manual control over middleware order is needed, especially to avoid conflicts with other middleware like API versioning. Note that settings from `ClsModule.forRoot()` are ignored and must be provided manually. ```typescript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ClsMiddleware } from 'nestjs-cls'; async function bootstrap() { const app = await NestFactory.create(AppModule); // create and mount the middleware manually here app.use( // highlight-start new ClsMiddleware({ /* ...settings */ }).use, // highlight-end ); await app.listen(3000); } ``` -------------------------------- ### Define Mongoose User Schema Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/07-mongoose-adapter.md Example of defining a Mongoose schema for a user. ```typescript const userSchema = new Schema({ name: String, email: String, }); const User = mongoose.model('user', userSchema); ``` -------------------------------- ### v5.x Proxy Provider Access Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/10_migration-guide/01_v5x-v6x.md Illustrates how to manage proxy providers using top-level methods on `ClsService` in v5.x. ```typescript await this.cls.resolveProxyProviders([MyProxyProvider]); this.cls.setProxy(MyOtherProxyProvider, new MyOtherProxyProvider(dependency)); const instance = this.cls.getProxy(SomeProxyProvider); ``` -------------------------------- ### ClsPluginHooks Interface Definition Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/02_plugin-api.md Defines the interface for CLS hooks within a plugin, allowing execution before and after the setup phase. ```typescript interface ClsPluginHooks { beforeSetup?: ( cls: ClsService, context: ClsInitContext, ) => void | Promise; afterSetup?: ( cls: ClsService, context: ClsInitContext, ) => void | Promise; } ``` -------------------------------- ### Manually Mount ClsMiddleware in Module Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/02_setting-up-cls-context/01_using-a-middleware.md Manually bind ClsMiddleware to specific routes by setting `middleware.mount` to `false` and using `consumer.apply(ClsMiddleware).forRoutes()` in the module's `configure` method. This provides more control over middleware order. ```typescript import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { ClsModule } from 'nestjs-cls'; import { ClsMiddleware } from 'nestjs-cls'; @Module({ imports: [ ClsModule.forRoot({ global: true, // highlight-start middleware: { mount: false }, // highlight-end }), ], // ... }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { // highlight-start consumer.apply(ClsMiddleware).forRoutes('custom/route'); // highlight-end } } ``` -------------------------------- ### Peer Dependency in package.json Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/05_considerations/03_for-library-authors.md List `nestjs-cls` as a peer dependency in your `package.json` to prevent multiple installations and potential DI errors. ```json { "peerDependencies": { "nestjs-cls": "^x.y.z" } } ``` -------------------------------- ### Get Data from CLS Storage Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/01_introduction/03_how-it-works.md Use `cls.get()` to retrieve data that was previously set using `cls.set()` within the current CLS context. ```javascript const requestId = cls.get('requestId'); ``` -------------------------------- ### UserRepository with Transaction Host Injection Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/07-mongoose-adapter.md Example of a UserRepository injecting TransactionHost to access the current transaction's ClientSession. This session is then passed to Mongoose queries. ```typescript @Injectable() class UserRepository { constructor( private readonly txHost: TransactionHost, ) {} async getUserById(id: ObjectId) { // txHost.tx is typed as ClientSession return await User.findById(id) // highlight-start .session(this.txHost.tx); // highlight-end } async createUser(name: string) { const user = new User({ name: name, email: `${name}@email.com` }); await user // highlight-start .save({ session: this.txHost.tx }); // highlight-end return user; } } ``` -------------------------------- ### Setup CLS in Enhancers (Interceptor/Guard) Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/03_features-and-use-cases/02_additional-cls-setup.md Configure CLS enhancers (like interceptors or guards) to set custom CLS values by accessing the request from the ExecutionContext. ```typescript ClsModule.forRoot({ interceptor: { mount: true, setup: (cls, context) => { const req = context.switchToHttp().getRequest(); cls.set('TENANT_ID', req.params['tenantId']); cls.set('AUTH', { authenticated: false }); }, }, }); ``` -------------------------------- ### Get DataSource Token with Custom Connection Name Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/05-typeorm-adapter.md When using @nestjs/typeorm with a custom connection name, retrieve the data source token using the getDataSourceToken function. ```typescript import { getDataSourceToken } from '@nestjs/typeorm'; // ... new TransactionalAdapterTypeOrm({ dataSourceToken: getDataSourceToken(), }); ``` -------------------------------- ### ClsMiddlewareOptions Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/04_api/02_module-options.md Options for configuring the CLS middleware. ```APIDOC ## ClsMiddlewareOptions ### Description Options for configuring the CLS middleware. ### Parameters #### Common Options - **mount** (boolean) - Optional - Whether to automatically mount the middleware to every route (default: `false`). Not applicable when instantiating manually. - **debug** (boolean) - Optional - Enable logging of debug messages (default: `true`). - **generateId** (boolean) - Optional - Whether to automatically generate a request ID. It will be available under the `CLS_ID` key (default: `false`). - **idGenerator** ((req: Request) => string | Promise) - Optional - A function for generating the request ID. It takes the `Request` object as an argument and returns a string. The default implementation uses `Math.random()`. - **setup** ((cls: ClsService, req: Request) => void | Promise) - Optional - Function that executes after the CLS context has been initialized. It can be used to put additional variables in the CLS context. - **resolveProxyProviders** (boolean) - Optional - Whether to automatically resolve Proxy Providers in the enhancer (default: `true`). - **initializePlugins** (boolean) - Optional - Whether to run the `onClsInit` hook for plugins (default: `true`). #### Middleware Specific Options - **saveReq** (boolean) - Optional - Whether to store the Request object to the context. It will be available under the `CLS_REQ` key (default: `true`). - **saveRes** (boolean) - Optional - Whether to store the Response object to the context. It will be available under the `CLS_RES` key (default: `false`). - **useEnterWith** (boolean) - Optional - Set to `true` to set up the context using `AsyncLocalStorage#enterWith` instead of `AsyncLocalStorage#run` (default: `false`). ``` -------------------------------- ### Inject Typed ClsService Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/03_features-and-use-cases/05_type-safety-and-type-inference.md Inject `ClsService` with a type parameter to enforce type safety when setting and getting values from the CLS context. Intellisense is provided for keys. ```typescript export class MyService { // highlight-start constructor(private readonly cls: ClsService) {} // highlight-end doTheThing() { // a boolean type will be enforced here this.cls.set('user.authorized', true); // tenantId will be inferred as a string const tenantId = this.cls.get('tenantId'); // userId will be inferred as a number const userId = this.cls.get('user.id'); // user will be inferred as { id: number, authorized: boolean } const user = this.cls.get('user'); // you'll even get intellisense for the keys, because the type // will be inferred as: // symbol | 'tenantId˙ | 'user' | 'user.id' | 'user.authorized' // alternatively, since the `get` method returns the whole store // when called without arguments, you can use object destructuring const { tenantId, user } = this.cls.get(); // accessing a nonexistent property will result in a type error const notExist = this.cls.get('user.name'); } } ``` -------------------------------- ### Custom Prisma Client Type Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/01-prisma-adapter.md Specify a custom Prisma client type as a generic parameter for the adapter when using extensions or a non-default setup. This ensures correct typing for the TransactionHost. ```typescript TransactionalAdapterPrisma; ``` ```typescript private readonly txHost: TransactionHost> ``` -------------------------------- ### Transactional User Creation and Retrieval Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/04-pg-promise-adapter.md Example of creating and retrieving a user within a single transaction using the @Transactional() decorator. The tx property on TransactionHost is typed as pg-promise's Database. ```typescript @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(user.id); // highlight-end assert(foundUser.id === user.id); } } ``` ```typescript @Injectable() class UserRepository { constructor( private readonly txHost: TransactionHost, ) {} async getUserById(id: number) { // highlight-start // txHost.tx is typed as Database return this.txHost.tx.one(`SELECT * FROM user WHERE id = $1`, [id]); // highlight-end } async createUser(name: string, email: string) { return this.txHost.tx.none( `INSERT INTO user (name, email) VALUES ($1, $2)`, [name, email], ); } } ``` -------------------------------- ### Initialize Module in Tests with Plugins or @UseCls() Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/10_migration-guide/01_v5x-v6x.md Shows the required `await module.init()` call in v6 tests when using CLS plugins or the `@UseCls()` decorator to ensure proper initialization. ```typescript const module = await Test.createTestingModule({ ... }).compile(); // highlight-start await module.init(); // required in v6 when using plugins or @UseCls() // highlight-end ``` -------------------------------- ### Configure ClsModule Synchronously Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/02_setting-up-cls-context/index.md Use `ClsModule.forRoot` for synchronous configuration of the CLS module, enabling global middleware with ID generation. ```typescript import { Module } from '@nestjs/common'; import { ClsModule } from 'nestjs-cls'; @Module({ imports: [ ClsModule.forRoot({ global: true, middleware: { mount: true, generateId: true, }, }), ], // ... }) export class AppModule {} ``` -------------------------------- ### Perform Transactional Operations with Knex Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/02-knex-adapter.md Example of performing multiple database operations within a single transaction using the @Transactional() decorator and UserRepository. The tx property on TransactionHost is typed as Knex. ```typescript @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); } } ``` ```typescript @Injectable() class UserRepository { constructor( private readonly txHost: TransactionHost, ) {} 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('*'); } } ``` -------------------------------- ### Deploy Website without SSH Source: https://github.com/papooch/nestjs-cls/blob/main/docs/README.md Builds the website and pushes it to the 'gh-pages' branch without using SSH. Requires setting the GIT_USER environment variable. ```bash GIT_USER= yarn deploy ``` -------------------------------- ### Use No-op Adapter with Mock Client Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/index.md Utilize the NoOpTransactionalAdapter from @nestjs-cls/transactional to enable @Transactional decorator compatibility without starting actual transactions. Provide a mock client via the `tx` option for the adapter. ```typescript const clientMock = { query: jest.fn(), }; const module = Test.createTestingModule({ imports: [ ClsModule.registerPlugins([ new ClsPluginTransactional({ // highlight-start adapter: new NoOpTransactionalAdapter({ tx: clientMock, }), // highlight-end }), ]), ], providers: [ServiceUnderTest], }); ``` -------------------------------- ### Configure ClsModule with Custom Transactional Adapter Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/99-creating-custom-adapter.md Use `ClsModule.forRoot` to configure the CLS module with a custom transactional adapter. Ensure to import necessary modules providing the database connection and any extra providers. ```typescript ClsModule.forRoot({ plugins: [ new ClsPluginTransactional({ // Don't forget to import the module which provides the knex instance imports: [KnexModule], // highlight-start adapter: new MyTransactionalAdapterKnex({ connectionToken: KNEX_TOKEN, defaultTxOptions: { isolationLevel: 'serializable' }, }), // highlight-end }), ], }), ``` -------------------------------- ### Execute Transactional Operations in UserService Source: https://github.com/papooch/nestjs-cls/blob/main/docs/docs/06_plugins/01_available-plugins/01-transactional/03-kysely-adapter.md Use the @Transactional() decorator on a method to ensure all database operations within that method are executed as a single transaction. This example demonstrates creating and retrieving a user within a transaction. ```typescript @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); } ```