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

fastify-router-oas

v2.2.1

Published

A library designed to connect Fastify application endpoints with the OPENAPI 3 scheme, which describes them. It supports validation for content type *application/json* and *multipart/form-data*, which is using as file upload.

Downloads

20

Readme

fastify-router-oas

A library designed to connect Fastify application endpoints with the OPENAPI 3 scheme, which describes them. It supports validation for content type application/json and multipart/form-data, which is using as file upload.

Compatibility

  • version 2.X.X is compatible with fastify 4.X.X
  • version 1.X.X is compatible with fastify 3.X.X (not maintained anymore)

Main components of the library:

  1. defining inputs/outputs of application endpoints
  2. automatic inputs/outputs validation of application endpoints based on the defined OPENAPI scheme
  3. multiple security support for individual endpoints
  4. automatic generation of a swagger ui, accessible via a web browser

Restrictions

~~1. library (due it's third party dependecy) can't resolve openapi $ref attribute, which points to external file~~ (resolved in version 2.2.0)

Usage

Usage is pretty simple, just register fastify-router-oas to application like this:

// some code above

fastify.register(fastifyRouterOas, {
  controllersPath: __dirname + '/controllers',
  openapiBaseDir: '.',
  openapiFilePath: './api.yaml',
  openapiUrlPath: '/swagger',
  security: {}
});

// some code below

Example

Let's create simple Fastify application:

// ./app.ts

import fastify from 'fastify';
import fastifyRouterOas from 'fastify-router-oas';


async function createServer() {
  const server = fastify();

  server.register(fastifyRouterOas, {
    controllersPath: __dirname + '/controllers',
    openapiBaseDir: '.',
    openapiFilePath: './api.yaml',
    openapiUrlPath: '/swagger',
    security: {}
  });

  return server;
}

createServer()
  .then((server) => {
    server.listen(3000, '0.0.0.0', (e, host) => {
      if (e) {
        throw e;
      }
      
      console.log(`Server listening on ${host}`);
    });
  })
  .catch((e) => {
    throw e;
  })

We need a controller in ./controllers directory:

// ./controllers/test.ts

export const testAction = async (req) => {
  // some logic

  return {
    status: 'OK'
  };
};

export const uploadFile = async (req) => {
  const file = req['file'];

  // some logic with file, which has following structure:
  // {
  //   fieldname: string,
  //   originalname: string,
  //   encoding: string,
  //   mimetype: string,
  //   buffer: Buffer,
  //   size: number
  // }

  return {
    'status': 'File uploaded!'
  };
};

Let's define OPENAPI schema for our two actions in controller above:

openapi: 3.0.2
info:
  version: 1.0.0
  title: fastify-router-oas example
servers:
  - url: /api/v1
paths:
  /test-action:
    x-controller: test
    get:
      operationId: testAction
      tags: [Test]
      responses:
        200:
          description: Test action
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
  /upload-file:
    x-controller: test
    post:
      operationId: uploadFile
      tags: [Test]
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                upload:
                  type: string
                  format: binary
      responses:
        200:
          description: File uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string

Usage of security

Usage of security contains to define a function, which provide security and attach it to definition of fastify-router-oas. It's something like following:

// some code above

fastify.register(fastifyRouterOas, {
  controllersPath: __dirname + '/controllers',
  openapiBaseDir: '.',
  openapiFilePath: './api.yaml',
  openapiUrlPath: '/swagger',
  security: {
    simple: simpleSecurity
  }
});

// some code below

async simpleSecurity(req: any): Promise<any> {
  // validation of api key, user access token or whatever...
}

To definition of OPENAPI we need to add security attribute:

...
/test-action:
  x-controller: test
  get:
    operationId: testAction
    tags: [Test]
    security:
      - simple: []
    responses:
      200:
        description: Test action
        ...

Conslusion

That's it! That simple way you can define your API by OPENAPI schema. Swagger UI you can find on defined path, as example above, you can find it at localhost:3000/swagger