CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nestjs--platform-fastify

Fastify-based HTTP adapter for the NestJS framework, enabling high-performance HTTP server integration with NestJS applications

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

fastify-adapter.mddocs/

HTTP Adapter

The FastifyAdapter class is the core component that integrates Fastify with NestJS, providing HTTP server functionality, lifecycle management, and middleware support.

Capabilities

FastifyAdapter Class

Main HTTP adapter that extends AbstractHttpAdapter and provides Fastify-specific functionality.

/**
 * Main HTTP adapter for integrating Fastify with NestJS
 * Supports multiple server types (HTTP, HTTPS, HTTP2) with generic type parameters
 */
class FastifyAdapter<
  TServer extends RawServerBase = RawServerDefault,
  TRawRequest extends FastifyRawRequest<TServer> = FastifyRawRequest<TServer>,
  TRawResponse extends RawReplyDefaultExpression<TServer> = RawReplyDefaultExpression<TServer>,
  TRequest extends FastifyRequest<RequestGenericInterface, TServer, TRawRequest> = FastifyRequest<RequestGenericInterface, TServer, TRawRequest>,
  TReply extends FastifyReply<RouteGenericInterface, TServer, TRawRequest, TRawResponse> = FastifyReply<RouteGenericInterface, TServer, TRawRequest, TRawResponse>,
  TInstance extends FastifyInstance<TServer, TRawRequest, TRawResponse> = FastifyInstance<TServer, TRawRequest, TRawResponse>
> extends AbstractHttpAdapter<TServer, TRequest, TReply> {
  constructor(
    instanceOrOptions?: 
      | TInstance 
      | FastifyHttp2Options<any>
      | FastifyHttp2SecureOptions<any>
      | FastifyHttpsOptions<any>
      | FastifyHttpOptions<any>
      | FastifyAdapterBaseOptions<TServer>
  );
}

Usage Examples:

import { FastifyAdapter } from '@nestjs/platform-fastify';
import { NestFactory } from '@nestjs/core';

// Basic adapter
const adapter = new FastifyAdapter();

// With options
const adapter = new FastifyAdapter({
  logger: true,
  bodyLimit: 1024 * 1024,
});

// With HTTPS
const adapter = new FastifyAdapter({
  https: {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  }
});

// With HTTP2
const adapter = new FastifyAdapter({
  http2: true,
  https: {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
  }
});

// Create NestJS app with adapter
const app = await NestFactory.create(AppModule, adapter);

Lifecycle Management

Methods for managing the adapter lifecycle and hooks.

/**
 * Sets a hook that runs before each request
 * @param hook - Function to execute on each request
 */
setOnRequestHook(
  hook: (
    request: TRequest,
    reply: TReply,
    done: (err?: Error) => void
  ) => void | Promise<void>
): void;

/**
 * Sets a hook that runs after each response
 * @param hook - Function to execute after each response
 */
setOnResponseHook(
  hook: (
    request: TRequest,
    reply: TReply,
    done: (err?: Error) => void
  ) => void | Promise<void>
): void;

/**
 * Initializes the adapter and registers necessary middleware
 * Must be called before starting the server
 */
init(): Promise<void>;

/**
 * Closes the server and cleans up resources
 */
close(): Promise<void>;

Server Operations

Methods for starting and managing the HTTP server.

/**
 * Starts the server listening on specified port
 * @param port - Port number or string
 * @param callback - Optional callback when server starts
 */
listen(port: string | number, callback?: () => void): void;

/**
 * Starts the server with hostname specification
 * @param port - Port number or string
 * @param hostname - Hostname to bind to
 * @param callback - Optional callback when server starts
 */
listen(port: string | number, hostname: string, callback?: () => void): void;

/**
 * Starts the server with Fastify listen options
 * @param listenOptions - Fastify listen configuration
 * @param args - Additional arguments
 */
listen(listenOptions: string | number | FastifyListenOptions, ...args: any[]): void;

/**
 * Returns the underlying HTTP server instance
 */
getHttpServer<T = TServer>(): T;

/**
 * Returns the Fastify instance
 */
getInstance<T = TInstance>(): T;

/**
 * Gets the adapter type identifier
 */
getType(): string; // Returns "fastify"

Route Registration

Methods for registering HTTP route handlers with various HTTP methods.

/**
 * Registers a GET route handler
 */
get(...args: any[]): any;

/**
 * Registers a POST route handler
 */
post(...args: any[]): any;

/**
 * Registers a PUT route handler
 */
put(...args: any[]): any;

/**
 * Registers a PATCH route handler
 */
patch(...args: any[]): any;

/**
 * Registers a DELETE route handler
 */
delete(...args: any[]): any;

/**
 * Registers a HEAD route handler
 */
head(...args: any[]): any;

/**
 * Registers an OPTIONS route handler
 */
options(...args: any[]): any;

/**
 * Registers a SEARCH route handler
 */
search(...args: any[]): any;

/**
 * Registers a PROPFIND route handler (WebDAV)
 */
propfind(...args: any[]): any;

/**
 * Registers a PROPPATCH route handler (WebDAV)
 */
proppatch(...args: any[]): any;

/**
 * Registers a MKCOL route handler (WebDAV)
 */
mkcol(...args: any[]): any;

/**
 * Registers a COPY route handler (WebDAV)
 */
copy(...args: any[]): any;

/**
 * Registers a MOVE route handler (WebDAV)
 */
move(...args: any[]): any;

/**
 * Registers a LOCK route handler (WebDAV)
 */
lock(...args: any[]): any;

/**
 * Registers an UNLOCK route handler (WebDAV)
 */
unlock(...args: any[]): any;

Response Handling

Methods for handling HTTP responses and status codes.

/**
 * Sends a response with optional status code
 * @param response - Response object (raw or Fastify reply)
 * @param body - Response body
 * @param statusCode - Optional HTTP status code
 */
reply(response: TRawResponse | TReply, body: any, statusCode?: number): any;

/**
 * Sets the response status code
 * @param response - Response object
 * @param statusCode - HTTP status code
 */
status(response: TRawResponse | TReply, statusCode: number): any;

/**
 * Ends the response
 * @param response - Response object
 * @param message - Optional message to send
 */
end(response: TReply, message?: string): void;

/**
 * Renders a view template
 * @param response - Response object with view method
 * @param view - View template name
 * @param options - Template options
 */
render(response: TReply & { view: Function }, view: string, options: any): any;

/**
 * Redirects the response
 * @param response - Response object
 * @param statusCode - Redirect status code
 * @param url - Target URL
 */
redirect(response: TReply, statusCode: number, url: string): any;

Header Management

Methods for managing HTTP headers.

/**
 * Checks if response headers have been sent
 * @param response - Response object
 */
isHeadersSent(response: TReply): boolean;

/**
 * Gets a response header value
 * @param response - Response object
 * @param name - Header name
 */
getHeader(response: any, name: string): string | undefined;

/**
 * Sets a response header
 * @param response - Response object
 * @param name - Header name
 * @param value - Header value
 */
setHeader(response: TReply, name: string, value: string): any;

/**
 * Appends a value to a response header
 * @param response - Response object
 * @param name - Header name
 * @param value - Header value to append
 */
appendHeader(response: any, name: string, value: string): void;

Request Information

Methods for extracting information from HTTP requests.

/**
 * Gets the request hostname
 * @param request - Request object
 */
getRequestHostname(request: TRequest): string;

/**
 * Gets the request HTTP method
 * @param request - Request object
 */
getRequestMethod(request: TRequest): string;

/**
 * Gets the request URL
 * @param request - Request object
 */
getRequestUrl(request: TRequest): string;
getRequestUrl(request: TRawRequest): string;

Plugin and Middleware Management

Methods for registering Fastify plugins and middleware.

/**
 * Registers a Fastify plugin
 * @param plugin - Fastify plugin
 * @param opts - Plugin options
 */
register<TRegister extends Parameters<FastifyRegister<FastifyInstance<TServer, TRawRequest, TRawResponse>>>>(
  plugin: TRegister['0'], 
  opts?: TRegister['1']
): Promise<TInstance>;

/**
 * Registers middleware (requires @fastify/middie)
 * @param args - Middleware arguments
 */
use(...args: any[]): this;

/**
 * Creates a middleware factory for specific request methods
 * @param requestMethod - HTTP request method
 */
createMiddlewareFactory(requestMethod: RequestMethod): Promise<(path: string, callback: Function) => any>;

Body Parsing

Methods for configuring request body parsing.

/**
 * Indicates if body parsers are registered
 */
readonly isParserRegistered: boolean;

/**
 * Registers default body parsers (JSON and URL-encoded)
 * @param prefix - Optional path prefix
 * @param rawBody - Whether to preserve raw body
 */
registerParserMiddleware(prefix?: string, rawBody?: boolean): void;

/**
 * Registers a custom body parser
 * @param type - Content type to parse
 * @param rawBody - Whether to preserve raw body
 * @param options - Parser options
 * @param parser - Custom parser function
 */
useBodyParser(
  type: string | string[] | RegExp,
  rawBody: boolean,
  options?: NestFastifyBodyParserOptions,
  parser?: FastifyBodyParser<Buffer, TServer>
): void;

Static Assets and View Engine

Methods for serving static files and configuring template engines.

/**
 * Configures static asset serving
 * @param options - Static asset configuration
 */
useStaticAssets(options: FastifyStaticOptions): Promise<TInstance>;

/**
 * Configures the view engine for template rendering
 * @param options - View engine configuration
 */
setViewEngine(options: FastifyViewOptions | string): Promise<TInstance>;

CORS Support

Method for enabling Cross-Origin Resource Sharing.

/**
 * Enables CORS with optional configuration
 * @param options - CORS configuration options
 */
enableCors(options?: FastifyCorsOptions): void;

Error Handling

Methods for configuring error and not found handlers.

/**
 * Sets a global error handler
 * @param handler - Error handling function
 */
setErrorHandler(handler: Parameters<TInstance['setErrorHandler']>[0]): any;

/**
 * Sets a handler for 404 not found responses
 * @param handler - Not found handling function
 */
setNotFoundHandler(handler: Function): any;

Testing Support

Method for injecting test requests.

/**
 * Injects a test request (returns chain for building request)
 */
inject(): LightMyRequestChain;

/**
 * Injects a test request with options
 * @param opts - Request options or URL string
 */
inject(opts: InjectOptions | string): Promise<LightMyRequestResponse>;

API Versioning

Method for applying version filters to route handlers.

/**
 * Applies version filtering to a route handler
 * @param handler - Route handler function
 * @param version - API version specification
 * @param versioningOptions - Versioning configuration
 */
applyVersionFilter(
  handler: Function,
  version: VersionValue,
  versioningOptions: VersioningOptions
): VersionedRoute<TRequest, TReply>;

Constructor Options Types

Base Options

interface FastifyAdapterBaseOptions<
  Server extends RawServerBase = RawServerDefault,
  Logger extends FastifyBaseLogger = FastifyBaseLogger
> extends FastifyServerOptions<Server, Logger> {
  /** Skip automatic registration of @fastify/middie middleware plugin */
  skipMiddie?: boolean;
}

HTTP2 Secure Options

interface FastifyHttp2SecureOptions<
  Server extends http2.Http2SecureServer,
  Logger extends FastifyBaseLogger = FastifyBaseLogger
> extends FastifyAdapterBaseOptions<Server, Logger> {
  http2: true;
  https: http2.SecureServerOptions;
}

HTTP2 Options

interface FastifyHttp2Options<
  Server extends http2.Http2Server,
  Logger extends FastifyBaseLogger = FastifyBaseLogger
> extends FastifyAdapterBaseOptions<Server, Logger> {
  http2: true;
  http2SessionTimeout?: number;
}

HTTPS Options

interface FastifyHttpsOptions<
  Server extends https.Server,
  Logger extends FastifyBaseLogger = FastifyBaseLogger
> extends FastifyAdapterBaseOptions<Server, Logger> {
  https: https.ServerOptions;
}

HTTP Options

interface FastifyHttpOptions<
  Server extends http.Server,
  Logger extends FastifyBaseLogger = FastifyBaseLogger
> extends FastifyAdapterBaseOptions<Server, Logger> {
  http: http.ServerOptions;
}

docs

decorators.md

fastify-adapter.md

index.md

interfaces.md

tile.json