UNPKG

@nestdevx/tenant

Version:

Tenant module for multi-tenant NestJS applications.

99 lines (80 loc) 2.22 kB
# @nestdevx/tenant Tenant module for multi-tenant NestJS applications. ## Overview This package provides a robust, reusable module for managing tenants in a multi-tenant NestJS application. It includes: - Tenant entity and DTOs - Tenant service and controller - Middleware for tenant context - Decorators for accessing the current tenant - CQRS event/query handlers ## Installation ```bash npm install @nestdevx/tenant # or yarn add @nestdevx/tenant # or pnpm add @nestdevx/tenant ``` ## Usage Example Import the `TenantModule` into your application or feature module: ```typescript import { Module } from '@nestjs/common'; import { TenantModule } from '@nestdevx/tenant'; @Module({ imports: [TenantModule], }) export class AppModule {} ``` ### Accessing the Current Tenant in a Controller ```typescript import { Controller, Get } from '@nestjs/common'; import { CurrentTenant } from '@nestdevx/tenant'; @Controller('tenants') export class TenantInfoController { @Protected() @Get() getTenant(@CurrentTenant() tenant) { return tenant; } } ``` ### Using CurrentTenantService in a Service You can inject `CurrentTenantService` into your own services to access the current tenant context programmatically: ```typescript import { Injectable } from '@nestjs/common'; import { CurrentTenantService } from '@nestdevx/tenant'; @Injectable() export class MyService { constructor(private readonly currentTenant: CurrentTenantService) {} getTenantId() { return this.currentTenant.id; } } ``` ### Registering Tenant Middleware If you want to use the tenant middleware for context resolution: ```typescript import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common'; import { TenantModule, TenantMiddleware } from '@nestdevx/tenant'; @Module({ imports: [TenantModule.register()], }) export class AppModule { configure(consumer: MiddlewareConsumer) { consumer .apply(TenantMiddleware) .forRoutes({ path: '*', method: RequestMethod.ALL }); } } ``` ## Exports - `TenantModule` - `TenantService` - `TenantController` - `CurrentTenantService` - `CurrentTenant` decorator - `TenantMiddleware` - Tenant entity and DTOs - CQRS event/query handlers ## License MIT