Poradnik · NestJS · Architektura heksagonalna
NestJS 11 w praktyce – moduły, DI, walidacja, Mongoose, kolejki i architektura heksagonalna
Przenosimy API zamówień pierogarni do NestJS 11 – moduły i wstrzykiwanie zależności, kontrolery i DTO z class-validator, pipe'y, guardy, interceptory i filtry wyjątków, konfiguracja walidowana Zodem, Mongoose 9, porty i adaptery, zadania cykliczne i kolejka BullMQ oraz testy z podmienionymi zależnościami.
Express daje ci wolność, NestJS – konwencję. Gdy API rośnie, a nad kodem pracuje kilka osób, wolność zamienia się w dziesięć różnych sposobów na to samo. NestJS narzuca moduły, wstrzykiwanie zależności (ang. dependency injection, DI) i jasny cykl życia żądania, a pod spodem nadal działa Express 5. W tym poradniku przenosimy API zamówień pierogarni z poradnika Express do NestJS 11 i układamy je tak, żeby baza danych i kolejka były wymiennymi adapterami.
Wymagania wstępne: Node.js 22+ (zalecany 24), Docker (dla MongoDB i Redisa), TypeScript z dekoratorami na poziomie „widziałem @Something() nad klasą”. Przyda się lektura poradnika Express – porównanie obu podejść jest pouczające.
- 11
- wersja NestJS – Express 5 pod spodem
- 2
- porty – repozytorium zamówień i bilety do kuchni
- 6
- etapów potoku żądania – middleware, guard, interceptor, pipe, handler, filtr
- 26
- plików w ZIP – z docker-compose i testami
Krok 1. Projekt i infrastruktura lokalna
Szkielet możesz wygenerować przez npx @nestjs/cli@11 new pierogi-nest, ale poniżej jest kompletna, odchudzona konfiguracja – bez ESLinta i Prettiera, żeby skupić się na NestJS.
npm install
cp .env.example .env
docker compose up -d # MongoDB 8 + Redis 8
npm run start:dev
Konfiguracja projektu
{
"name": "pierogi-nest",
"version": "1.0.0",
"private": true,
"scripts": {
"build": "nest build",
"start": "nest start",
"start:dev": "nest start --watch",
"start:prod": "node dist/main",
"typecheck": "tsc --noEmit",
"test": "jest"
},
"dependencies": {
"@nestjs/bullmq": "^11.0.5",
"@nestjs/common": "^11.2.12",
"@nestjs/config": "^4.0.4",
"@nestjs/core": "^11.2.12",
"@nestjs/mongoose": "^11.0.4",
"@nestjs/platform-express": "^11.2.12",
"@nestjs/schedule": "^6.1.3",
"@nestjs/throttler": "^6.8.0",
"bullmq": "^6.7.10",
"class-transformer": "^0.5.1",
"class-validator": "^0.15.1",
"helmet": "^8.3.0",
"ioredis": "^6.1.0",
"mongoose": "^9.13.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"zod": "^4.6.7"
},
"devDependencies": {
"@nestjs/cli": "^11.0.24",
"@nestjs/schematics": "^11.1.0",
"@nestjs/testing": "^11.2.12",
"@types/express": "^5.0.6",
"@types/jest": "^30.0.0",
"@types/node": "^24.19.4",
"jest": "^30.5.2",
"ts-jest": "^29.4.15",
"typescript": "~5.9.3"
},
"jest": {
"moduleFileExtensions": ["js", "json", "ts"],
"testRegex": ".*\\.spec\\.ts$",
"transform": { "^.+\\.(t|j)s$": "ts-jest" },
"testEnvironment": "node"
}
}{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"target": "ES2023",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"esModuleInterop": true,
"isolatedModules": true,
"strict": true,
"strictPropertyInitialization": false,
"skipLibCheck": true,
"sourceMap": true,
"outDir": "./dist",
"incremental": true,
"types": ["node", "jest"]
},
"include": ["src", "test"]
}{
"extends": "./tsconfig.json",
"include": ["src"]
}{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": { "deleteOutDir": true }
}NODE_ENV=development
PORT=3000
MONGODB_URI=mongodb://localhost:27017/pierogi
REDIS_URL=redis://localhost:6379
CORS_ORIGINS=http://localhost:5173
# openssl rand -hex 32
KITCHEN_API_KEY=replace-with-a-long-random-secret-of-32-chars# Local infrastructure only – the app itself runs with `npm run start:dev`.
services:
mongo:
image: mongo:8
ports: ["27017:27017"]
volumes: [mongo-data:/data/db]
redis:
image: redis:8-alpine
ports: ["6379:6379"]
volumes:
mongo-data:Dwie opcje w tsconfig.json są dla Nesta obowiązkowe: experimentalDecorators (dekoratory w starym, „legacy” wariancie) i emitDecoratorMetadata – kompilator zapisuje typy parametrów konstruktora, a kontener DI odczytuje z nich, co wstrzyknąć. TypeScript zostaje na 5.9: Nest CLI 11 korzysta z API kompilatora, którego TypeScript 7 już nie udostępnia.
Krok 2. Konfiguracja i moduł główny
ConfigModule.forRoot() czyta .env i zmienne środowiskowe, a opcja validate pozwala podpiąć dowolny walidator. Używamy tego samego schematu Zod co w Expressie – aplikacja nie wstanie z brakującym MONGODB_URI albo za krótkim kluczem kuchni.
Konfiguracja, AppModule i bootstrap
import { z } from 'zod';
const EnvSchema = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
MONGODB_URI: z.string().startsWith('mongodb'),
REDIS_URL: z.string().startsWith('redis').default('redis://localhost:6379'),
CORS_ORIGINS: z.string().default('http://localhost:5173'),
// Shared secret for the kitchen tablet – long and random.
KITCHEN_API_KEY: z.string().min(32),
});
export type Env = z.infer<typeof EnvSchema>;
// Plugged into ConfigModule: the app refuses to start with a broken config.
export function validateEnv(raw: Record<string, unknown>): Env {
const result = EnvSchema.safeParse(raw);
if (!result.success) {
throw new Error(`Invalid environment configuration:\n${z.prettifyError(result.error)}`);
}
return result.data;
}import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { MongooseModule } from '@nestjs/mongoose';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { DomainExceptionFilter } from './common/filters/domain-exception.filter';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { Env, validateEnv } from './config/env';
import { OrdersModule } from './orders/orders.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true, cache: true, validate: validateEnv }),
MongooseModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({ uri: config.get('MONGODB_URI', { infer: true }) }),
}),
BullModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService<Env, true>) => ({ connection: { url: config.get('REDIS_URL', { infer: true }) } }),
}),
ScheduleModule.forRoot(),
ThrottlerModule.forRoot([{ ttl: 60_000, limit: 120 }]),
OrdersModule,
],
providers: [
// Global enhancers registered as providers can use dependency injection.
{ provide: APP_GUARD, useClass: ThrottlerGuard },
{ provide: APP_FILTER, useClass: DomainExceptionFilter },
{ provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
],
})
export class AppModule {}import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import helmet from 'helmet';
import { AppModule } from './app.module';
import type { Env } from './config/env';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = app.get<ConfigService<Env, true>>(ConfigService);
app.use(helmet());
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }).split(','), credentials: true });
app.setGlobalPrefix('api');
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // strip properties without decorators
forbidNonWhitelisted: true, // ...or rather reject them with 400
transform: true, // turn payloads into DTO class instances (and apply defaults)
}),
);
app.enableShutdownHooks(); // SIGTERM -> onModuleDestroy / beforeApplicationShutdown
await app.listen(config.get('PORT', { infer: true }));
}
void bootstrap();Co tu się dzieje:
ConfigService<Env, true>z{ infer: true }daje typowany odczyt –config.get('PORT', { infer: true })zwracanumber, a literówka w nazwie zmiennej nie kompiluje się.forRootAsync+inject: [ConfigService]to standardowy sposób, żeby moduł infrastruktury (Mongoose, BullMQ) dostał konfigurację z DI, zamiast czytaćprocess.envw losowych miejscach.APP_GUARD,APP_FILTER,APP_INTERCEPTORrejestrują globalne elementy potoku jako providery – mogą wstrzykiwać zależności.app.useGlobalFilters(new X())wmain.tstego nie potrafi.ValidationPipezwhitelistiforbidNonWhitelistedodrzuca pola, których DTO nie zna (np."admin": true), atransformzamienia JSON w instancje klas DTO.
Krok 3. Domena i porty
Zanim dotkniemy Nesta, opisujemy pierogarnię w czystym TypeScripcie: typy, reguły i błędy domenowe. Ten plik nie importuje niczego z @nestjs/* ani mongoose.
Domena zamówień i porty
// Pure domain: no Nest, no Mongoose – just the rules of Halina's kitchen.
export const DISHES = ['ruskie', 'z-miesem', 'z-kapusta', 'z-jagodami'] as const;
export const ORDER_STATUSES = ['new', 'in-kitchen', 'ready', 'delivered', 'cancelled'] as const;
export const MAX_PIEROGI_PER_ORDER = 100;
export type Dish = (typeof DISHES)[number];
export type OrderStatus = (typeof ORDER_STATUSES)[number];
export interface OrderItem {
dish: Dish;
quantity: number;
}
export interface Order {
id: string;
customerName: string;
phone: string;
items: OrderItem[];
note?: string;
status: OrderStatus;
createdAt: Date;
}
export type NewOrder = Omit<Order, 'id' | 'status' | 'createdAt'>;
export class DomainError extends Error {
constructor(
readonly code: string,
message: string,
) {
super(message);
}
}
export class OrderNotFoundError extends DomainError {
constructor(id: string) {
super('ORDER_NOT_FOUND', `Order ${id} not found`);
}
}
export class TooManyPierogiError extends DomainError {
constructor(total: number) {
super('TOO_MANY_PIEROGI', `Max ${MAX_PIEROGI_PER_ORDER} pierogi per order, got ${total}`);
}
}
export class InvalidTransitionError extends DomainError {
constructor(from: OrderStatus, to: OrderStatus) {
super('INVALID_TRANSITION', `Cannot move order from "${from}" to "${to}"`);
}
}
const TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {
new: ['in-kitchen', 'cancelled'],
'in-kitchen': ['ready', 'cancelled'],
ready: ['delivered'],
delivered: [],
cancelled: [],
};
export function assertValidOrder(order: NewOrder): void {
const total = order.items.reduce((sum, item) => sum + item.quantity, 0);
if (total > MAX_PIEROGI_PER_ORDER) throw new TooManyPierogiError(total);
}
export function assertTransition(from: OrderStatus, to: OrderStatus): void {
if (!TRANSITIONS[from].includes(to)) throw new InvalidTransitionError(from, to);
}import type { NewOrder, Order, OrderStatus } from './order';
// Ports as abstract classes: they exist at runtime, so Nest can use them as DI tokens.
export abstract class OrdersRepository {
abstract create(order: NewOrder): Promise<Order>;
abstract findById(id: string): Promise<Order | null>;
abstract list(filter: { status?: OrderStatus; limit: number }): Promise<Order[]>;
abstract updateStatus(id: string, status: OrderStatus): Promise<Order | null>;
abstract deleteCancelledBefore(date: Date): Promise<number>;
}
export abstract class KitchenTickets {
abstract send(order: Order): Promise<void>;
}Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Krok 4. Serwis aplikacyjny
- Krok 5. Kontroler, DTO i pipe'y
- Krok 6. Guardy, interceptory i filtry wyjątków
- Krok 7. Mongoose: schemat, adapter i moduł
- Krok 8. Zadania w tle: kolejka i harmonogram
- Krok 9. Testy z podmienionymi adapterami
- Typowe błędy
- Kiedy NestJS, a kiedy nie
- Sprawdź się
- Co dalej