npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@platformatic/fastify-openapi-glue

v5.0.0

Published

generate a fastify configuration from an openapi specification

Downloads

4,117

Readme

Fastify OpenApi Glue

A plugin for fastify to autogenerate a configuration based on a OpenApi(v2/v3) specification.

Given an OpenApi specification Fastify-openapi-glue handles the fastify configuration of routes and validation schemas etc.

Install

npm i @platformatic/fastify-openapi-glue --save

Plugin

Usage

Add the plugin to your project with register and pass it some basic options and you are done !

import openapiGlue from "@platformatic/fastify-openapi-glue";
import { Service } from "./service.js";
import { Security } from "./security.js";

const options = {
  specification: `${currentDir}/petstore-openapi.v3.json`,
  serviceHandlers: new Service(),
  securityHandlers: new Security(),
  prefix: "v1",
};


fastify.register(openapiGlue, options);

All schema and routes will be taken from the OpenApi specification listed in the options. No need to specify them in your code.

Options

  • specification: this can be a JSON object, or the name of a JSON or YAML file containing a valid OpenApi(v2/v3) file
  • serviceHandlers: this can be a javascript object or class instance. See the serviceHandlers documentation for more details.
  • securityHandlers: this can be a javascript object or class instance. See the securityHandlers documentation for more details.
  • prefix: this is a string that can be used to prefix the routes, it is passed verbatim to fastify. E.g. if the path to your operation is specified as "/operation" then a prefix of "v1" will make it available at "/v1/operation". This setting overrules any "basePath" setting in a v2 specification. See the servers documentation for more details on using prefix with a v3 specification.
  • operationResolver: a custom operation resolver function, (operationId, method, openapiPath) => handler | routeOptions where method is the uppercase HTTP method (e.g. "GET") and openapiPath is the path taken from the specification without prefix (e.g. "/operation"). Mutually exclusive with serviceHandlers. See the operationResolver documentation for more details.
  • addEmptySchema: a boolean that allows empty bodies schemas to be passed through. This might be useful for status codes like 204 or 304. Default is false.

specification and either serviceHandlers or operationResolver are mandatory, securityHandlers and prefix are optional.

Please be aware that this will refer to your serviceHandlers object or your securityHandler object and not to Fastify as explained in the bindings documentation

OpenAPI extensions

The OpenAPI specification supports extending an API spec to describe extra functionality that isn't covered by the official specification. Extensions start with x- (e.g., x-myapp-logo) and can contain a primitive, an array, an object, or null.

The following extensions are provided by the plugin:

  • x-fastify-config (object): any properties will be added to the routeOptions.config property of the Fastify route.

    For example, if you wanted to use the fastify-raw-body plugin to compute a checksum of the request body, you could add the following extension to your OpenAPI spec to signal the plugin to specially handle this route:

    paths:
      /webhooks:
        post:
          operationId: processWebhook
          x-fastify-config:
            rawBody: true
          responses:
            204:
              description: Webhook processed successfully
  • x-no-fastify-config (true): this will ignore this specific route as if it was not present in your OpenAPI specification:

  paths:
    /webhooks:
      post:
        operationId: processWebhook
        x-no-fastify-config: true
        responses:
          204:
            description: Webhook processed successfully

You can also set custom OpenAPI extensions (e.g., x-myapp-foo) for use within your app's implementation. These properties are passed through unmodified to the Fastify route on {req,reply}.routeOptions.config. Extensions specified on a schema are also accessible (e.g., routeOptions.schema.body or routeOptions.schema.responses[<statusCode>]).

Notes

  • the plugin ignores information in a v3 specification under server/url as there could be multiple values here, use the prefix option if you need to prefix your routes. See the servers documentation for more details.
  • fastify only supports application/json and text/plain out of the box. The default charset is utf-8. If you need to support different content types, you can use the fastify addContentTypeParser API.
  • fastify will by default coerce types, e.g when you expect a number a string like "1" will also pass validation, this can be reconfigured, see Validation and Serialization.
  • fastify only supports one schema per route. So while the v3 standard allows for multiple content types per route, each with their own schema this is currently not going to work with fastify. Potential workarounds include a custom content type parser and merging schemas upfront using JSON schema oneOf.
  • the plugin aims to follow fastify and does not compensate for features that are possible according to the OpenApi specification but not possible in standard fastify (without plugins). This will keep the plugin lightweigth and maintainable. E.g. Fastify does not support cookie validation, while OpenApi v3 does.
  • in some cases however, the plugin may be able to provide you with data which could be used to enhance OpenApi support within your own Fastify application. Here is one possible way to perform cookie validation yourself.
  • if you have special needs on querystring handling (e.g. arrays, objects etc) then fastify supports a custom querystring parser. You might need to pass the AJV option coerceTypes: 'array' as an option to Fastify.
  • the plugin is an ECMAscript Module (aka ESM). If you are using Typescript then make sure that you have read: https://www.typescriptlang.org/docs/handbook/esm-node.html to avoid any confusion.
  • If you want to use a specification that consists of multiple files then please check out the page on subschemas
  • Fastify uses AJV strict mode in validating schemas. If you get an error like ....due to error strict mode: unknown keyword: "..." then please check out the page on AJV strict mode

Contributing

  • contributions are always welcome.
  • if you plan on submitting new features then please create an issue first to discuss and avoid disappointments.
  • main development is done on the master branch therefore PRs to that branch are preferred.
  • please make sure you have run npm test before you submit a PR.

Credits

This module was forked from https://github.com/seriousme/fastify-openapi-glue at commit afb4ac65a4d4c7d1bf53c0d245ed134a8f1b5689 We thank Hans Klunder for his original work on this module.

License

Licensed under MIT