การสร้างโมดูลไดนามิกที่กำหนดค่าได้
สร้างตัวให้บริการแบบ forRoot และ forRootAsync ด้วย ConfigurableModuleBuilder สำหรับโมดูลผู้เช่าที่นำกลับมาใช้ซ้ำได้
การสร้างโมดูลไดนามิกที่กำหนดค่าได้ เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Dynamic Modules?
A regular NestJS module exports a fixed set of providers. But a reusable module — like a tenant resolver, a cache client, or an HTTP wrapper — needs configuration from the consumer: a connection string, an API key, a tenant strategy.
A dynamic module is a module whose providers, imports, and exports are computed at import time from caller-supplied options. The convention is a static factory method, almost always named forRoot() (or register()), that returns a DynamicModule object.
forRoot()— configure once, globally (DB, tenant registry)register()— configure per-import, possibly multiple timesforFeature()— register feature-scoped sub-resources
The DynamicModule Shape
A static factory must return an object matching the DynamicModule interface. The key extra field is module, which points back to the host class. Everything else mirrors a normal @Module() decorator.
Here a TenantModule.forRoot() turns caller options into a provider keyed by a token, then exports it so other modules can inject it.
import { DynamicModule, Module } from '@nestjs/common';
export interface TenantOptions {
registryUrl: string;
defaultTenant: string;
}
export const TENANT_OPTIONS = 'TENANT_OPTIONS';
@Module({})
export class TenantModule {
static forRoot(options: TenantOptions): DynamicModule {
return {
module: TenantModule,
providers: [{ provide: TENANT_OPTIONS, useValue: options }],
exports: [TENANT_OPTIONS],
};
}
}Consuming forRoot
The consumer imports the dynamic module by calling the factory, not just referencing the class. The returned options provider becomes injectable anywhere inside the module's scope.
A service injects the TENANT_OPTIONS token to read its configuration.
import { Inject, Injectable, Module } from '@nestjs/common';
import { TenantModule, TENANT_OPTIONS, TenantOptions } from './tenant.module';
@Injectable()
export class TenantService {
constructor(@Inject(TENANT_OPTIONS) private readonly opts: TenantOptions) {}
resolve(header?: string): string {
return header ?? this.opts.defaultTenant;
}
}
@Module({
imports: [
TenantModule.forRoot({
registryUrl: 'https://registry.internal/tenants',
defaultTenant: 'acme',
}),
],
})
export class AppModule {}The Problem: Async Configuration
Synchronous forRoot(options) works only when you already hold the literal values. In real backends the registryUrl lives in ConfigService, a secrets manager, or another async source.
That is why reusable modules expose a second factory: forRootAsync(). It lets the caller provide options via useFactory, useClass, or useExisting — and crucially, to inject other providers that resolve the values.
- useFactory — inline async function returning the options
- useClass / useExisting — a class implementing an options factory interface
Hand-Rolled forRootAsync
Before reaching for helpers, it is worth seeing the mechanics. forRootAsync accepts an async-options object, declares an imports list (so ConfigModule is visible), and wires the caller's useFactory into the options provider.
The factory's inject array feeds dependencies into useFactory, exactly like any provider.
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { TenantOptions, TENANT_OPTIONS } from './tenant.module';
export interface TenantAsyncOptions {
imports?: any[];
inject?: any[];
useFactory: (...args: any[]) => Promise<TenantOptions> | TenantOptions;
}
@Module({})
export class TenantModule {
static forRootAsync(async: TenantAsyncOptions): DynamicModule {
const optionsProvider: Provider = {
provide: TENANT_OPTIONS,
useFactory: async.useFactory,
inject: async.inject ?? [],
};
return {
module: TenantModule,
imports: async.imports ?? [],
providers: [optionsProvider],
exports: [TENANT_OPTIONS],
};
}
}Calling forRootAsync
Now the consumer pulls values from ConfigService at runtime. The imports field makes ConfigModule available inside the dynamic module so the factory can inject ConfigService.
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TenantModule } from './tenant.module';
@Module({
imports: [
ConfigModule.forRoot(),
TenantModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
registryUrl: config.getOrThrow<string>('TENANT_REGISTRY_URL'),
defaultTenant: config.get<string>('DEFAULT_TENANT', 'acme'),
}),
}),
],
})
export class AppModule {}Enter ConfigurableModuleBuilder
Writing both factories by hand is boilerplate that every reusable module repeats. Since NestJS 9, ConfigurableModuleBuilder generates the forRoot/forRootAsync plumbing for you from a single options type.
You create a small *.module-definition.ts file that calls the builder and exports:
ConfigurableModuleClass— a base class your module extendsMODULE_OPTIONS_TOKEN— the injection token for the resolved optionsOPTIONS_TYPE/ASYNC_OPTIONS_TYPE— typed signatures for the generated methods
Defining the Module Definition
The builder is generic over your options interface. Calling .build() returns everything the module needs. Your module then extends ConfigurableModuleClass and instantly gains forRoot() and forRootAsync().
import { ConfigurableModuleBuilder } from '@nestjs/common';
export interface TenantModuleOptions {
registryUrl: string;
defaultTenant: string;
}
export const {
ConfigurableModuleClass,
MODULE_OPTIONS_TOKEN,
OPTIONS_TYPE,
ASYNC_OPTIONS_TYPE,
} = new ConfigurableModuleBuilder<TenantModuleOptions>().build();Wiring the Module Class
The host module extends the generated base class and registers its real providers. Services inject MODULE_OPTIONS_TOKEN to read the resolved options — whether they came from forRoot or forRootAsync, the token is the same.
Note: when you add your own providers/exports alongside the generated ones, keep the @Module() decorator — the builder merges its dynamic part with your static metadata.
import { Module } from '@nestjs/common';
import {
ConfigurableModuleClass,
MODULE_OPTIONS_TOKEN,
} from './tenant.module-definition';
import { TenantService } from './tenant.service';
@Module({
providers: [TenantService],
exports: [TenantService, MODULE_OPTIONS_TOKEN],
})
export class TenantModule extends ConfigurableModuleClass {}Custom Method Name & Extra Options
The builder is configurable. Use .setClassMethodName('register') when per-import registration reads better than forRoot. Use .setExtras() to add fields that are not part of the injected options — typically isGlobal — and a transform that injects them into the DynamicModule (e.g. setting global: true).
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { TenantModuleOptions } from './tenant.types';
export interface TenantExtras {
isGlobal?: boolean;
}
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<TenantModuleOptions>()
.setExtras<TenantExtras>(
{ isGlobal: false },
(definition, extras) => ({
...definition,
global: extras.isGlobal,
}),
)
.setClassMethodName('register')
.build();Multi-Tenancy Payoff
Put together, a tenant module becomes a drop-in dependency for any service in the platform. A request-scoped provider can resolve the active tenant from a header, falling back to the configured default — all driven by options the consuming app supplied via register/registerAsync.
The key insight: configuration flows through one token (MODULE_OPTIONS_TOKEN), so internal services never care whether setup was sync or async, literal or factory-resolved.
import { Inject, Injectable, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { MODULE_OPTIONS_TOKEN } from './tenant.module-definition';
import { TenantModuleOptions } from './tenant.types';
@Injectable({ scope: Scope.REQUEST })
export class TenantContext {
constructor(
@Inject(MODULE_OPTIONS_TOKEN) private readonly opts: TenantModuleOptions,
@Inject(REQUEST) private readonly req: Request,
) {}
get tenantId(): string {
const header = this.req.headers['x-tenant-id'];
return (Array.isArray(header) ? header[0] : header) ?? this.opts.defaultTenant;
}
}Quick Check
Your reusable TenantModule must read its registryUrl from ConfigService, which itself loads asynchronously at bootstrap. Which approach lets the consumer wire this correctly?
Recap
You built a configurable dynamic module end to end:
- A dynamic module returns a
DynamicModulefrom a static factory (forRoot/register), turning caller options into a token-backed provider. - forRootAsync adds
imports,inject, anduseFactoryso options can be resolved fromConfigServiceor other async sources. ConfigurableModuleBuildergenerates both factories from one options type, exposingConfigurableModuleClassandMODULE_OPTIONS_TOKEN..setClassMethodName()renames the factory;.setExtras()adds out-of-band flags likeisGlobal.- All internal services inject the same options token, staying agnostic to how configuration was supplied — the foundation for reusable multi-tenant modules.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “การสร้างโมดูลไดนามิกที่กำหนดค่าได้” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างโมดูลไดนามิกที่กำหนดค่าได้” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างโมดูลไดนามิกที่กำหนดค่าได้”
สร้างตัวให้บริการแบบ forRoot และ forRootAsync ด้วย ConfigurableModuleBuilder สำหรับโมดูลผู้เช่าที่นำกลับมาใช้ซ้ำได้ คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างโมดูลไดนามิกที่กำหนดค่าได้” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การระบุผู้เช่าผ่านมิดเดิลแวร์และ AsyncLocalStorage
- การเชื่อมต่อฐานข้อมูลแบบแยกสคีมาตามผู้เช่า
- การสร้างโมดูลไดนามิกที่กำหนดค่าได้
- ตัวให้บริการตามขอบเขตคำขอและข้อแลกเปลี่ยน