{"id":"6b09417e5ce40d447918f2cb","slug":"nestjs","title":"NestJS 11 w praktyce – moduły, DI, walidacja, Mongoose, kolejki i architektura heksagonalna","summary":"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.","servedLang":"pl","availableLangs":["pl","en"],"topics":["nestjs","hexagonal-architecture","express"],"techs":["node","typescript"],"tags":["nestjs-11","dependency-injection","class-validator","mongoose","bullmq","scheduling","guards","interceptors","jest"],"level":"intermediate","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":23,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:22.920Z","updatedAt":"2026-11-27T10:04:16.023Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"NestJS 11 krok po kroku – moduły, providery i DI, DTO z class-validator, ValidationPipe, guardy, interceptory, filtry wyjątków, @nestjs/config, Mongoose, porty i adaptery, @nestjs/schedule, BullMQ i testy jednostkowe.","wordCount":4476,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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. "},{"type":"text","text":"dependency injection","marks":[{"type":"italic"}]},{"type":"text","text":", DI) i jasny cykl życia żądania, a pod spodem nadal działa Express 5. W tym poradniku przenosimy API zamówień pierogarni z "},{"type":"text","text":"poradnika Express","marks":[{"type":"link","attrs":{"href":"/pl/articles/express"}}]},{"type":"text","text":" do NestJS 11 i układamy je tak, żeby baza danych i kolejka były wymiennymi adapterami."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Moduł grupuje kontrolery i providery","marks":[{"type":"bold"}]},{"type":"text","text":", a kontener DI tworzy obiekty i wstrzykuje je przez konstruktor. Ty deklarujesz zależności, Nest składa graf."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Żądanie przechodzi przez stały potok","marks":[{"type":"bold"}]},{"type":"text","text":": middleware → guardy → interceptory → pipe'y → kontroler → (interceptory) → filtry wyjątków. Każdy etap ma jedno zadanie."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Porty jako klasy abstrakcyjne","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"OrdersRepository","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"KitchenTickets","marks":[{"type":"code"}]},{"type":"text","text":") są jednocześnie tokenami DI. Serwis zależy od portów, a Mongo i BullMQ podpinasz jedną linijką w module – i podmieniasz w testach."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"pierogi-nest","marks":[{"type":"code"}]},{"type":"text","text":": to samo API zamówień co w Expressie ("},{"type":"text","text":"POST/GET /api/orders","marks":[{"type":"code"}]},{"type":"text","text":", zmiana statusu z kluczem kuchni), ale z MongoDB przez Mongoose 9, kolejką BullMQ, która „drukuje” bilecik do kuchni, nocnym sprzątaniem anulowanych zamówień ("},{"type":"text","text":"@Cron","marks":[{"type":"code"}]},{"type":"text","text":"), globalnym limitem żądań i testami serwisu bez bazy i Redisa. Kod (26 plików) pobierzesz jako ZIP; "},{"type":"text","text":"docker compose up -d","marks":[{"type":"code"}]},{"type":"text","text":" uruchamia MongoDB i Redis, "},{"type":"text","text":"npm run start:dev","marks":[{"type":"code"}]},{"type":"text","text":" – aplikację."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22+ (zalecany 24), Docker (dla MongoDB i Redisa), TypeScript z dekoratorami na poziomie „widziałem "},{"type":"text","text":"@Something()","marks":[{"type":"code"}]},{"type":"text","text":" nad klasą”. Przyda się lektura "},{"type":"text","text":"poradnika Express","marks":[{"type":"link","attrs":{"href":"/pl/articles/express"}}]},{"type":"text","text":" – porównanie obu podejść jest pouczające."}]},{"type":"stats","attrs":{"items":[{"value":"11","label":"wersja NestJS","hint":"Express 5 pod spodem"},{"value":"2","label":"porty","hint":"repozytorium zamówień i bilety do kuchni"},{"value":"6","label":"etapów potoku żądania","hint":"middleware, guard, interceptor, pipe, handler, filtr"},{"value":"26","label":"plików w ZIP","hint":"z docker-compose i testami"}]}},{"type":"callout","attrs":{"variant":"info","title":"NestJS 11 czy 12?"},"content":[{"type":"paragraph","content":[{"type":"text","text":"W sierpniu 2026 ukazał się NestJS 12, którego pakiety są modułami ESM. Ten poradnik trzyma się linii 11.x – w npm oznaczonej tagiem "},{"type":"text","text":"legacy","marks":[{"type":"code"}]},{"type":"text","text":", ale wciąż regularnie łatanej i używanej w większości istniejących projektów (na niej działa też ten portal). Moduły, DI, dekoratory i cykl życia żądania wyglądają w obu wersjach tak samo; przy przejściu na 12 zmienia się głównie konfiguracja modułów i narzędzi – sprawdź oficjalny przewodnik migracji."}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-i-infrastruktura-lokalna"},"content":[{"type":"text","text":"Krok 1. Projekt i infrastruktura lokalna"}]},{"type":"paragraph","content":[{"type":"text","text":"Szkielet możesz wygenerować przez "},{"type":"text","text":"npx @nestjs/cli@11 new pierogi-nest","marks":[{"type":"code"}]},{"type":"text","text":", ale poniżej jest kompletna, odchudzona konfiguracja – bez ESLinta i Prettiera, żeby skupić się na NestJS."}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"npm install\ncp .env.example .env\ndocker compose up -d      # MongoDB 8 + Redis 8\nnpm run start:dev"}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja projektu"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-nest\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"build\": \"nest build\",\n    \"start\": \"nest start\",\n    \"start:dev\": \"nest start --watch\",\n    \"start:prod\": \"node dist/main\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"test\": \"jest\"\n  },\n  \"dependencies\": {\n    \"@nestjs/bullmq\": \"^11.0.5\",\n    \"@nestjs/common\": \"^11.2.12\",\n    \"@nestjs/config\": \"^4.0.4\",\n    \"@nestjs/core\": \"^11.2.12\",\n    \"@nestjs/mongoose\": \"^11.0.4\",\n    \"@nestjs/platform-express\": \"^11.2.12\",\n    \"@nestjs/schedule\": \"^6.1.3\",\n    \"@nestjs/throttler\": \"^6.8.0\",\n    \"bullmq\": \"^6.7.10\",\n    \"class-transformer\": \"^0.5.1\",\n    \"class-validator\": \"^0.15.1\",\n    \"helmet\": \"^8.3.0\",\n    \"ioredis\": \"^6.1.0\",\n    \"mongoose\": \"^9.13.1\",\n    \"reflect-metadata\": \"^0.2.2\",\n    \"rxjs\": \"^7.8.2\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@nestjs/cli\": \"^11.0.24\",\n    \"@nestjs/schematics\": \"^11.1.0\",\n    \"@nestjs/testing\": \"^11.2.12\",\n    \"@types/express\": \"^5.0.6\",\n    \"@types/jest\": \"^30.0.0\",\n    \"@types/node\": \"^24.19.4\",\n    \"jest\": \"^30.5.2\",\n    \"ts-jest\": \"^29.4.15\",\n    \"typescript\": \"~5.9.3\"\n  },\n  \"jest\": {\n    \"moduleFileExtensions\": [\"js\", \"json\", \"ts\"],\n    \"testRegex\": \".*\\\\.spec\\\\.ts$\",\n    \"transform\": { \"^.+\\\\.(t|j)s$\": \"ts-jest\" },\n    \"testEnvironment\": \"node\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"target\": \"ES2023\",\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"esModuleInterop\": true,\n    \"isolatedModules\": true,\n    \"strict\": true,\n    \"strictPropertyInitialization\": false,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"incremental\": true,\n    \"types\": [\"node\", \"jest\"]\n  },\n  \"include\": [\"src\", \"test\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.build.json"},"content":[{"type":"text","text":"{\n  \"extends\": \"./tsconfig.json\",\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"nest-cli.json"},"content":[{"type":"text","text":"{\n  \"$schema\": \"https://json.schemastore.org/nest-cli\",\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": { \"deleteOutDir\": true }\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":".env.example"},"content":[{"type":"text","text":"NODE_ENV=development\nPORT=3000\nMONGODB_URI=mongodb://localhost:27017/pierogi\nREDIS_URL=redis://localhost:6379\nCORS_ORIGINS=http://localhost:5173\n# openssl rand -hex 32\nKITCHEN_API_KEY=replace-with-a-long-random-secret-of-32-chars"}]},{"type":"codeBlock","attrs":{"language":"yaml","filename":"docker-compose.yml"},"content":[{"type":"text","text":"# Local infrastructure only – the app itself runs with `npm run start:dev`.\nservices:\n  mongo:\n    image: mongo:8\n    ports: [\"27017:27017\"]\n    volumes: [mongo-data:/data/db]\n  redis:\n    image: redis:8-alpine\n    ports: [\"6379:6379\"]\nvolumes:\n  mongo-data:"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Dwie opcje w "},{"type":"text","text":"tsconfig.json","marks":[{"type":"code"}]},{"type":"text","text":" są dla Nesta obowiązkowe: "},{"type":"text","text":"experimentalDecorators","marks":[{"type":"code"}]},{"type":"text","text":" (dekoratory w starym, „legacy” wariancie) i "},{"type":"text","text":"emitDecoratorMetadata","marks":[{"type":"code"}]},{"type":"text","text":" – 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."}]},{"type":"callout","attrs":{"variant":"warning","title":"BullMQ 6 potrzebuje ioredis"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Od wersji 6 BullMQ traktuje "},{"type":"text","text":"ioredis","marks":[{"type":"code"}]},{"type":"text","text":" jako opcjonalną zależność (można podać inny klient Redisa). Bez "},{"type":"text","text":"npm install ioredis","marks":[{"type":"code"}]},{"type":"text","text":" aplikacja wystartuje, ale worker co chwilę zaloguje „BullMQ could not load the optional 'ioredis' package”. W "},{"type":"text","text":"package.json","marks":[{"type":"code"}]},{"type":"text","text":" powyżej jest już dopisany."}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-konfiguracja-i-modul-glowny"},"content":[{"type":"text","text":"Krok 2. Konfiguracja i moduł główny"}]},{"type":"paragraph","content":[{"type":"text","text":"ConfigModule.forRoot()","marks":[{"type":"code"}]},{"type":"text","text":" czyta "},{"type":"text","text":".env","marks":[{"type":"code"}]},{"type":"text","text":" i zmienne środowiskowe, a opcja "},{"type":"text","text":"validate","marks":[{"type":"code"}]},{"type":"text","text":" pozwala podpiąć dowolny walidator. Używamy tego samego schematu Zod co w Expressie – aplikacja nie wstanie z brakującym "},{"type":"text","text":"MONGODB_URI","marks":[{"type":"code"}]},{"type":"text","text":" albo za krótkim kluczem kuchni."}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja, AppModule i bootstrap"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/config/env.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nconst EnvSchema = z.object({\n  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),\n  PORT: z.coerce.number().int().min(1).max(65535).default(3000),\n  MONGODB_URI: z.string().startsWith('mongodb'),\n  REDIS_URL: z.string().startsWith('redis').default('redis://localhost:6379'),\n  CORS_ORIGINS: z.string().default('http://localhost:5173'),\n  // Shared secret for the kitchen tablet – long and random.\n  KITCHEN_API_KEY: z.string().min(32),\n});\n\nexport type Env = z.infer<typeof EnvSchema>;\n\n// Plugged into ConfigModule: the app refuses to start with a broken config.\nexport function validateEnv(raw: Record<string, unknown>): Env {\n  const result = EnvSchema.safeParse(raw);\n  if (!result.success) {\n    throw new Error(`Invalid environment configuration:\\n${z.prettifyError(result.error)}`);\n  }\n  return result.data;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/app.module.ts"},"content":[{"type":"text","text":"import { BullModule } from '@nestjs/bullmq';\nimport { Module } from '@nestjs/common';\nimport { ConfigModule, ConfigService } from '@nestjs/config';\nimport { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { ScheduleModule } from '@nestjs/schedule';\nimport { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';\nimport { DomainExceptionFilter } from './common/filters/domain-exception.filter';\nimport { LoggingInterceptor } from './common/interceptors/logging.interceptor';\nimport { Env, validateEnv } from './config/env';\nimport { OrdersModule } from './orders/orders.module';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({ isGlobal: true, cache: true, validate: validateEnv }),\n    MongooseModule.forRootAsync({\n      inject: [ConfigService],\n      useFactory: (config: ConfigService<Env, true>) => ({ uri: config.get('MONGODB_URI', { infer: true }) }),\n    }),\n    BullModule.forRootAsync({\n      inject: [ConfigService],\n      useFactory: (config: ConfigService<Env, true>) => ({ connection: { url: config.get('REDIS_URL', { infer: true }) } }),\n    }),\n    ScheduleModule.forRoot(),\n    ThrottlerModule.forRoot([{ ttl: 60_000, limit: 120 }]),\n    OrdersModule,\n  ],\n  providers: [\n    // Global enhancers registered as providers can use dependency injection.\n    { provide: APP_GUARD, useClass: ThrottlerGuard },\n    { provide: APP_FILTER, useClass: DomainExceptionFilter },\n    { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },\n  ],\n})\nexport class AppModule {}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/main.ts"},"content":[{"type":"text","text":"import { ValidationPipe } from '@nestjs/common';\nimport { ConfigService } from '@nestjs/config';\nimport { NestFactory } from '@nestjs/core';\nimport helmet from 'helmet';\nimport { AppModule } from './app.module';\nimport type { Env } from './config/env';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  const config = app.get<ConfigService<Env, true>>(ConfigService);\n\n  app.use(helmet());\n  app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }).split(','), credentials: true });\n  app.setGlobalPrefix('api');\n  app.useGlobalPipes(\n    new ValidationPipe({\n      whitelist: true, // strip properties without decorators\n      forbidNonWhitelisted: true, // ...or rather reject them with 400\n      transform: true, // turn payloads into DTO class instances (and apply defaults)\n    }),\n  );\n  app.enableShutdownHooks(); // SIGTERM -> onModuleDestroy / beforeApplicationShutdown\n\n  await app.listen(config.get('PORT', { infer: true }));\n}\n\nvoid bootstrap();"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Co tu się dzieje:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ConfigService<Env, true>","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"{ infer: true }","marks":[{"type":"code"}]},{"type":"text","text":" daje typowany odczyt – "},{"type":"text","text":"config.get('PORT', { infer: true })","marks":[{"type":"code"}]},{"type":"text","text":" zwraca "},{"type":"text","text":"number","marks":[{"type":"code"}]},{"type":"text","text":", a literówka w nazwie zmiennej nie kompiluje się."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"forRootAsync","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"inject: [ConfigService]","marks":[{"type":"code"}]},{"type":"text","text":" to standardowy sposób, żeby moduł infrastruktury (Mongoose, BullMQ) dostał konfigurację z DI, zamiast czytać "},{"type":"text","text":"process.env","marks":[{"type":"code"}]},{"type":"text","text":" w losowych miejscach."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"APP_GUARD","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"APP_FILTER","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"APP_INTERCEPTOR","marks":[{"type":"code"}]},{"type":"text","text":" rejestrują globalne elementy potoku "},{"type":"text","text":"jako providery","marks":[{"type":"bold"}]},{"type":"text","text":" – mogą wstrzykiwać zależności. "},{"type":"text","text":"app.useGlobalFilters(new X())","marks":[{"type":"code"}]},{"type":"text","text":" w "},{"type":"text","text":"main.ts","marks":[{"type":"code"}]},{"type":"text","text":" tego nie potrafi."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ValidationPipe","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"whitelist","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"forbidNonWhitelisted","marks":[{"type":"code"}]},{"type":"text","text":" odrzuca pola, których DTO nie zna (np. "},{"type":"text","text":"\"admin\": true","marks":[{"type":"code"}]},{"type":"text","text":"), a "},{"type":"text","text":"transform","marks":[{"type":"code"}]},{"type":"text","text":" zamienia JSON w instancje klas DTO."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"krok-3-domena-i-porty"},"content":[{"type":"text","text":"Krok 3. Domena i porty"}]},{"type":"paragraph","content":[{"type":"text","text":"Zanim dotkniemy Nesta, opisujemy pierogarnię w czystym TypeScripcie: typy, reguły i błędy domenowe. Ten plik nie importuje niczego z "},{"type":"text","text":"@nestjs/*","marks":[{"type":"code"}]},{"type":"text","text":" ani "},{"type":"text","text":"mongoose","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"codeGroup","attrs":{"title":"Domena zamówień i porty"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/domain/order.ts"},"content":[{"type":"text","text":"// Pure domain: no Nest, no Mongoose – just the rules of Halina's kitchen.\nexport const DISHES = ['ruskie', 'z-miesem', 'z-kapusta', 'z-jagodami'] as const;\nexport const ORDER_STATUSES = ['new', 'in-kitchen', 'ready', 'delivered', 'cancelled'] as const;\nexport const MAX_PIEROGI_PER_ORDER = 100;\n\nexport type Dish = (typeof DISHES)[number];\nexport type OrderStatus = (typeof ORDER_STATUSES)[number];\n\nexport interface OrderItem {\n  dish: Dish;\n  quantity: number;\n}\n\nexport interface Order {\n  id: string;\n  customerName: string;\n  phone: string;\n  items: OrderItem[];\n  note?: string;\n  status: OrderStatus;\n  createdAt: Date;\n}\n\nexport type NewOrder = Omit<Order, 'id' | 'status' | 'createdAt'>;\n\nexport class DomainError extends Error {\n  constructor(\n    readonly code: string,\n    message: string,\n  ) {\n    super(message);\n  }\n}\n\nexport class OrderNotFoundError extends DomainError {\n  constructor(id: string) {\n    super('ORDER_NOT_FOUND', `Order ${id} not found`);\n  }\n}\n\nexport class TooManyPierogiError extends DomainError {\n  constructor(total: number) {\n    super('TOO_MANY_PIEROGI', `Max ${MAX_PIEROGI_PER_ORDER} pierogi per order, got ${total}`);\n  }\n}\n\nexport class InvalidTransitionError extends DomainError {\n  constructor(from: OrderStatus, to: OrderStatus) {\n    super('INVALID_TRANSITION', `Cannot move order from \"${from}\" to \"${to}\"`);\n  }\n}\n\nconst TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {\n  new: ['in-kitchen', 'cancelled'],\n  'in-kitchen': ['ready', 'cancelled'],\n  ready: ['delivered'],\n  delivered: [],\n  cancelled: [],\n};\n\nexport function assertValidOrder(order: NewOrder): void {\n  const total = order.items.reduce((sum, item) => sum + item.quantity, 0);\n  if (total > MAX_PIEROGI_PER_ORDER) throw new TooManyPierogiError(total);\n}\n\nexport function assertTransition(from: OrderStatus, to: OrderStatus): void {\n  if (!TRANSITIONS[from].includes(to)) throw new InvalidTransitionError(from, to);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/domain/ports.ts"},"content":[{"type":"text","text":"import type { NewOrder, Order, OrderStatus } from './order';\n\n// Ports as abstract classes: they exist at runtime, so Nest can use them as DI tokens.\nexport abstract class OrdersRepository {\n  abstract create(order: NewOrder): Promise<Order>;\n  abstract findById(id: string): Promise<Order | null>;\n  abstract list(filter: { status?: OrderStatus; limit: number }): Promise<Order[]>;\n  abstract updateStatus(id: string, status: OrderStatus): Promise<Order | null>;\n  abstract deleteCancelledBefore(date: Date): Promise<number>;\n}\n\nexport abstract class KitchenTickets {\n  abstract send(order: Order): Promise<void>;\n}"}]}]}]},"toc":[{"id":"krok-1-projekt-i-infrastruktura-lokalna","text":"Krok 1. Projekt i infrastruktura lokalna","level":2,"locked":false},{"id":"krok-2-konfiguracja-i-modul-glowny","text":"Krok 2. Konfiguracja i moduł główny","level":2,"locked":false},{"id":"krok-3-domena-i-porty","text":"Krok 3. Domena i porty","level":2,"locked":false},{"id":"krok-4-serwis-aplikacyjny","text":"Krok 4. Serwis aplikacyjny","level":2,"locked":true},{"id":"krok-5-kontroler-dto-i-pipe-y","text":"Krok 5. Kontroler, DTO i pipe'y","level":2,"locked":true},{"id":"krok-6-guardy-interceptory-i-filtry-wyjatkow","text":"Krok 6. Guardy, interceptory i filtry wyjątków","level":2,"locked":true},{"id":"krok-7-mongoose-schemat-adapter-i-modul","text":"Krok 7. Mongoose: schemat, adapter i moduł","level":2,"locked":true},{"id":"krok-8-zadania-w-tle-kolejka-i-harmonogram","text":"Krok 8. Zadania w tle: kolejka i harmonogram","level":2,"locked":true},{"id":"krok-9-testy-z-podmienionymi-adapterami","text":"Krok 9. Testy z podmienionymi adapterami","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"kiedy-nestjs-a-kiedy-nie","text":"Kiedy NestJS, a kiedy nie","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":67,"visibleBlocks":20,"resources":[{"id":"6b0857b23c96f2d34d0b33bb","type":"repo","provider":"github","url":"https://github.com/nestjs/nest","embedUrl":null,"title":"nestjs/nest","description":"A progressive TypeScript framework for Node.js backends: from a small API in one file to efficient, scalable, enterprise-grade systems 🚀","author":"nestjs","thumbnailUrl":"https://opengraph.githubassets.com/1/nestjs/nest","durationSec":null,"lang":"en","topics":["microservices"],"techs":["node","javascript","typescript"],"tags":["framework","hacktoberfest","javascript","javascript-framework","microservices","nest","system-design","nestjs","node","nodejs"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2017-02-04T20:12:52.000Z","popularity":94,"verifiedAt":"2026-11-26T10:58:32.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857b23c96f2d34d0b357d","type":"repo","provider":"github","url":"https://github.com/jmcdo29/testing-nestjs","embedUrl":null,"title":"jmcdo29/testing-nestjs","description":"A repository to show off to the community methods of testing NestJS including Unit Tests, Integration Tests, E2E Tests, pipes, filters, interceptors, GraphQL, Mongo, TypeORM, and more!","author":"jmcdo29","thumbnailUrl":"https://opengraph.githubassets.com/1/jmcdo29/testing-nestjs","durationSec":null,"lang":"en","topics":["cqrs"],"techs":["node","typescript"],"tags":["cqrs","examples","graphql","hacktoberfest","interceptor","mongo","testing","api-design","nestjs","pipes"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2019-07-25T21:14:54.000Z","popularity":67,"verifiedAt":"2026-11-26T10:58:16.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857b23c96f2d34d0b35ac","type":"repo","provider":"github","url":"https://github.com/Sairyss/backend-best-practices","embedUrl":null,"title":"Sairyss/backend-best-practices","description":"Best practices, tools and guidelines for backend development. Code examples in TypeScript + NodeJS","author":"Sairyss","thumbnailUrl":"https://opengraph.githubassets.com/1/Sairyss/backend-best-practices","durationSec":null,"lang":"en","topics":[],"techs":["node","javascript","typescript"],"tags":["backend","best-practices","api","software-design","typescript","javascript","devops","nodejs","nestjs","development"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2021-12-16T11:12:26.000Z","popularity":65,"verifiedAt":"2026-11-26T10:55:56.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857b33c96f2d34d0b3602","type":"repo","provider":"github","url":"https://github.com/pvarentsov/typescript-clean-architecture","embedUrl":null,"title":"pvarentsov/typescript-clean-architecture","description":"It is my attempt to create Clean Architecture based application in TypeScript.","author":"pvarentsov","thumbnailUrl":"https://opengraph.githubassets.com/1/pvarentsov/typescript-clean-architecture","durationSec":null,"lang":"en","topics":["clean-architecture"],"techs":["node","typescript"],"tags":["back-end","clean-architecture","clean-code","e2e-testing","nestjs","nodejs","software-architecture","testing","typeorm","typescript"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2020-07-07T17:19:36.000Z","popularity":61,"verifiedAt":"2026-11-26T10:57:47.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"},{"id":"6b0857ab3c96f2d34d0b326e","type":"package","provider":"npm","url":"https://www.npmjs.com/package/@nestjs/cqrs","embedUrl":null,"title":"@nestjs/cqrs","description":"CQRS for NestJS: command, query and event buses, sagas.","author":"","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["cqrs","event-driven-architecture"],"techs":["node"],"tags":["cqrs"],"price":"free","featured":false,"featuredOrder":29,"packageName":"@nestjs/cqrs","source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:43.175Z","updatedAt":"2026-11-26T16:00:43.175Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}