Skip to content

Commit acfdfd4

Browse files
authored
doc: update the documentation for WithContext to prevent bugs (#18)
1 parent fe23154 commit acfdfd4

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

README.md

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -461,21 +461,21 @@ export class NestedService {
461461

462462
**Message Handlers**: Add service identification and correlation tracking
463463
```typescript
464-
@WithContext(() => ({ correlationId: uuid(), handler: 'user.validate' }))
465464
@MessagePattern('user.validate')
465+
@WithContext(() => ({ correlationId: uuid(), handler: 'user.validate' }))
466466
async validateUser(@Payload() data: ValidateUserDto) {
467467
this.logger.log('Validating user credentials');
468468
}
469469
```
470470

471471
**Cron Jobs**: Track scheduled task execution
472472
```typescript
473+
@Cron('0 2 * * *')
473474
@WithContext(() => ({
474475
task: 'data-sync',
475476
executionId: uuid(),
476477
scheduledAt: new Date().toISOString()
477478
}))
478-
@Cron('0 2 * * *')
479479
async syncUserData() {
480480
this.logger.log('Starting user data synchronization');
481481
}
@@ -489,6 +489,28 @@ async processEmailBatch(emails: Email[]) {
489489
}
490490
```
491491

492+
### Decorator Positioning
493+
494+
**⚠️ IMPORTANT**: When using `@WithContext`, it **must be placed closer to the function definition** than other decorators to ensure proper context initialization.
495+
496+
```typescript
497+
// ✅ Correct - @WithContext closer to function
498+
@MessagePattern('user.created')
499+
@WithContext(() => ({ correlationId: uuid() }))
500+
async handleUserCreated(data: CreateUserDto) {
501+
this.logger.log('Processing user creation');
502+
}
503+
504+
// ❌ Incorrect - @WithContext too far from function
505+
@WithContext(() => ({ correlationId: uuid() }))
506+
@MessagePattern('user.created')
507+
async handleUserCreated(data: CreateUserDto) {
508+
this.logger.log('Processing user creation'); // Context may not be available
509+
}
510+
```
511+
512+
This applies to all NestJS decorators including `@MessagePattern`, `@EventPattern`, `@Cron`, etc.
513+
492514
### When to Use @WithContext vs updateContext()
493515

494516
**Use `@WithContext` for:**
@@ -545,6 +567,23 @@ async processEmailBatch(emails: Email[]) {
545567
logger.info('Item fetched id: 1, time: 2000, source: serviceA');
546568
```
547569

570+
4. **Position @WithContext Correctly**
571+
```typescript
572+
// ✅ Good - @WithContext farther from function
573+
@MessagePattern('user.created')
574+
@WithContext(() => ({ correlationId: uuid() }))
575+
async handleUserCreated(data: CreateUserDto) {
576+
this.logger.log('Processing user creation');
577+
}
578+
579+
// ❌ Not good - @WithContext too close to function
580+
@WithContext(() => ({ correlationId: uuid() }))
581+
@MessagePattern('user.created')
582+
async handleUserCreated(data: CreateUserDto) {
583+
this.logger.log('Processing user creation');
584+
}
585+
```
586+
548587
# Performance Considerations
549588

550589
This logger uses `AsyncLocalStorage` to maintain context, which does add an overhead.

src/decorators/with-context.decorator.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,20 @@ import { ContextStore } from '../store/context-store';
77
*
88
* @example
99
* ```typescript
10-
* @WithContext()
1110
* @MessagePattern('user.created')
11+
* @WithContext()
1212
* async handleUserCreated(data: CreateUserDto) {
1313
* this.logger.log('Processing user creation');
1414
* }
1515
*
16-
* @WithContext({ userId: 'user_123' })
1716
* @Cron('0 0 * * *')
17+
* @WithContext({ userId: 'user_123' })
1818
* async dailyReport() {
1919
* this.logger.log('Running daily report');
2020
* }
2121
*
22-
* @WithContext(() => ({ correlationId: uuid(), service: 'UserService' }))
2322
* @MessagePattern('user.validate')
23+
* @WithContext(() => ({ correlationId: uuid(), service: 'UserService' }))
2424
* async validateUser(data: ValidateUserDto) {
2525
* this.logger.log('Validating user'); // Fresh correlationId each call
2626
* }

0 commit comments

Comments
 (0)