Transport & Patterns — Series 2

Preview — 3 of 10 questions

How does this differ from NestFactory.create(AppModule)?

javascript
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.TCP,
  options: { host: '0.0.0.0', port: 3001 },
});
await app.listen();
AIt builds a second copy of the module graph, separate from the HTTP application's
BIt creates an application with no HTTP server: the same modules, controllers and providers are used, but requests arrive over the configured transport and are matched to @MessagePattern/@EventPattern handlers instead of routes
CIt disables dependency injection, since messages carry their own context
DIt runs the application in a worker thread

Why is @Controller() used here even though there are no routes?

javascript
@Controller()
export class MathController {
  @MessagePattern({ cmd: 'sum' })
  sum(@Payload() data: number[]): number {
    return data.reduce((a, b) => a + b, 0);
  }
}
AIt is a leftover requirement with no meaning outside HTTP
B@MessagePattern only works on classes that also declare at least one HTTP route
CThe decorator registers the class as a provider, and message handlers are discovered on providers
D@Controller() is what registers the class as an entry point in the module, and Nest's scanner then discovers both HTTP routes and message patterns on it — a controller is simply "a class that handles incoming requests", whatever the transport

What happens to the returned value?

javascript
@EventPattern('order.created')
async handleOrderCreated(@Payload() data: OrderCreatedEvent) {
  await this.mailer.sendConfirmation(data);
  return { ok: true };      // ???
}
ANothing — events are fire-and-forget, so the publisher never receives a response and the return value is discarded; only @MessagePattern handlers send a reply
BIt is sent back to the publisher, which receives it through emit()'s Observable
CIt is republished as a new event on the same pattern
DIt is stored by the transport for later retrieval by the publisher

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.