Skip to content

Server

reference
1 min readUpdated

Kind: Class

Source: packages/microservices/server/server.ts

Part of: Microservices

Server is the base class for microservice transport servers. It manages message-handler registration and lookup, transport identification, and processing lifecycle hooks while allowing concrete transport implementations to provide connection, listening, shutdown, and native-client behavior.

Methods

MethodSignatureReturns
onon(event: EventKey, callback: EventCallback)any
unwrapunwrap()T
listenlisten(callback: (...optionalParams: unknown[]) => any)any
closeclose()any
setTransportId`setTransportId(transportId: Transportsymbol)`
setOnProcessingStartHook`setOnProcessingStartHook(hook: ( transportId: Transportsymbol, context: unknown, done: () => Promise, ) => void)`
setOnProcessingEndHook`setOnProcessingEndHook(hook: (transportId: Transportsymbol, context: unknown) => void)`
addHandleraddHandler(pattern: any, callback: MessageHandler, isEventHandler: undefined, extras: Record<string, any>)void
getHandlersgetHandlers()Map<string, MessageHandler>
getHandlerByPatterngetHandlerByPattern(pattern: string)`MessageHandler
send`send(stream$: Observable, respond: (data: WritePacket) => Promisevoid)`
handleEventhandleEvent(pattern: string, packet: ReadPacket, context: BaseRpcContext)Promise<any>
transformToObservable`transformToObservable(resultOrDeferred: ObservablePromise)`
transformToObservabletransformToObservable(resultOrDeferred: T)never extends Observable<ObservedValueOf<T>> ? Observable<T> : Observable<ObservedValueOf<T>>
transformToObservabletransformToObservable(resultOrDeferred: any)void
getOptionsPropgetOptionsProp(obj: Options, prop: Attribute)Options[Attribute]
getOptionsPropgetOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)Required<Options>[Attribute]
getOptionsPropgetOptionsProp(obj: Options, prop: Attribute, defaultValue: DefaultValue)void
handleErrorhandleError(error: string)void
loadPackageloadPackage(name: string, ctx: string, loader: Function)T
initializeSerializerinitializeSerializer(options: ClientOptions['options'])void
initializeDeserializerinitializeDeserializer(options: ClientOptions['options'])void
getRouteFromPatterngetRouteFromPattern(pattern: string)string
normalizePatternnormalizePattern(pattern: MsPattern)string

Properties

PropertyType
transportId`Transport
messageHandlersany
loggerLoggerService
serializerConsumerSerializer
deserializerConsumerDeserializer
onProcessingStartHook`( transportId: Transport
onProcessingEndHook`( transportId: Transport
_status$any

Where it refuses work

  • Server stops the work with an early return when !handler.
  • Server stops the work with an early return when resultOrDeferred instanceof Promise.
  • Server stops the work with an early return when isObservable(resultOrDeferred).

When something fails

  • Server handles failure in 1 place: it logs it and continues in all 1.

Diagram

mermaid
graph LR
  Client[Microservice Client] --> Transport[Concrete Server Transport]
  Transport --> Server[Server Base Class]
  Server --> Handlers[Message Handler Map]
  Server --> StartHook[Processing Start Hook]
  Server --> EndHook[Processing End Hook]
  Handlers --> Handler[Message Handler]
  Handler --> Response[Response or Event Processing]

Usage

ts
import { Server } from '@nestjs/microservices';

class CustomServer extends Server {
  async listen(callback: () => void) {
    // Connect to the underlying transport here.
    callback();
  }

  async close() {
    // Close transport connections and release resources.
  }

  unwrap<T>() {
    // Return the underlying transport client/server instance.
    return {} as T;
  }
}

const server = new CustomServer();

server.setTransportId('custom-transport');

server.setOnProcessingStartHook(() => {
  console.log('Started processing message');
});

server.setOnProcessingEndHook(() => {
  console.log('Finished processing message');
});

server.addHandler('users.find', async (payload) => {
  return { id: payload.id, name: 'Ada Lovelace' };
});

await server.listen(() => {
  console.log('Custom microservice server is listening');
});

const handler = server.getHandlerByPattern('users.find');

if (handler) {
  const result = await handler({ id: 'user-1' });
  console.log(result);
}

await server.close();

AI Coding Instructions

  • Extend Server when implementing a new transport; provide transport-specific listen(), close(), and unwrap() implementations.
  • Register request and event handlers through addHandler() rather than mutating the handler map returned by getHandlers().
  • Use the same normalized message pattern when registering handlers and retrieving them with getHandlerByPattern().
  • Set a transport ID with setTransportId() when the transport must be identified by framework integrations or diagnostics.
  • Keep processing hooks lightweight; use setOnProcessingStartHook() and setOnProcessingEndHook() for instrumentation, tracing, or metrics rather than business logic.

Was this page helpful?

Download as PDF
Server — NestJS head-to-head