openapi-fastify
    Preparing search index...

    Class OpenApiRouter<T>

    OpenApiRouter is a class that integrates OpenAPI specifications with Fastify routing.

    import Fastify from "fastify";
    import { OpenApiRouter } from "./router";

    const app = Fastify();
    const openApiDoc = { ... }; // Your OpenAPI document/specification
    const router = new OpenApiRouter(app, openApiDoc);

    router.route("/hello", {
    get: router.op(
    <const>{
    operationId: "getHello",
    responses: { 200: { description: "Hello response" } }
    },
    async (request, reply) => {
    reply.send({ message: "Hello, world!" });
    }
    )
    });

    router.initialize();

    Type Parameters

    • T

      The type representing the OpenAPI document.

    Index

    Constructors

    Properties

    app: FastifyInstance

    The Fastify instance used for registering routes.

    document: T

    The OpenAPI document used for schema references and validation.

    options: RouterOptions = {}

    Optional configuration for the router.

    routes: { methods: OperatorRecord; path: string }[] = []

    Stores the registered routes and their method handlers.

    Accessors

    • get specification(): OpenAPI.Document

      Returns OpenAPI.Document

      The OpenAPI specification.

      • Returns the OpenAPI specification.
      • This method should be called after all routes have been registered.
      const spec = $.specification;
      console.log(spec.paths['/users']);

    Methods

    • Parameters

      Returns Promise<
          FastifyInstance<
              RawServerDefault,
              IncomingMessage,
              ServerResponse<IncomingMessage>,
              FastifyBaseLogger,
              FastifyTypeProviderDefault,
          >,
      >

      The Fastify instance.

      • Autoloads routes from the specified directory.
      $.autoload({ include: ['**/*.ts'], exclude: ['*.exclude.*'] });
      
    • Type Parameters

      Parameters

      • handler: Method<T>

        The handler function.

      Returns Method<T>

      The handler function.

      • Creates a handler function with the specified OpenAPI specification.
      const spec = $.spec(<const>{
      summary: "Create a new user",
      requestBody: {
      required: true,
      content: {
      "application/json": {
      schema: $.ref('#/components/schemas/User')
      }
      }
      },
      responses: {
      200: {
      description: "User created",
      content: {
      "application/json": {
      schema: $.ref('#/components/schemas/User')
      }
      }
      }
      }
      })
      $.handler<typeof spec>(async (request) => {
      return {id: 1, username: "alice", email: "alice@example.com", role: "user"};
      })
    • Returns FastifyInstance<
          RawServerDefault,
          IncomingMessage,
          ServerResponse<IncomingMessage>,
          FastifyBaseLogger,
          FastifyTypeProviderDefault,
      >

      The Fastify instance.

      • Initializes the router and registers all routes with Fastify.
      $.initialize();
      
    • Type Parameters

      Parameters

      • specification: T

        The OpenAPI specification.

      • handler: Method<T>

        The handler function.

      Returns Router.Operator<T>

      The operator object.

      Creates an operation handler with OpenAPI specification and type-safe handler function.

       $.op(
      <const>{
      summary: "Create a new user",
      requestBody: {
      required: true,
      content: {
      "application/json": {
      schema: $.ref('#/components/schemas/User')
      }
      }
      },
      responses: {
      201: $.ref('#/components/responses/UserCreated')
      }
      },
      async (request, reply) => {
      const { username, email, password, role } = request.body as any;
      const user = dbHelpers.addUser({ username, email, password, role });
      const { password: _, ...rest } = user;
      reply.code(201);
      return rest;
      }
      )
    • Type Parameters

      • S extends never

      Parameters

      • ref: S

        The reference string.

      • options: { useRef?: boolean } = ...

        The options for the reference.

      Returns ComponentFromRef<T, S>

      The referenced schema object.

      Creates a reference to a schema in the OpenAPI document.

      $.ref('#/components/schemas/User') // returns `{type: 'object', properties: {...}}`
      
      $.ref('#/components/schemas/User', {useRef: true}) // returns `{$ref: '#/components/schemas/User'}`
      
    • Parameters

      • path: string

        The path of the route.

      • methods: OperatorRecord

        The HTTP methods of the route.

      Returns { methods: OperatorRecord; path: string }

      The route object.

      Registers a new route with the specified path and HTTP methods.

      $.route("/users", {
      post: $.op(
      <const>{
      summary: "Create a new user",
      requestBody: {
      required: true,
      content: {
      "application/json": {
      schema: $.ref('#/components/schemas/User')
      }
      }
      },
      responses: {
      201: $.ref('#/components/responses/UserCreated')
      }
      },
      async (request, reply) => {
      const { username, email, password, role } = request.body as any;
      const user = dbHelpers.addUser({ username, email, password, role });
      const { password: _, ...rest } = user;
      reply.code(201);
      return rest;
      }
      )
      });