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

wingnut

v0.3.0

Published

API validation middleware builder based on Open API V3 specs

Downloads

149

Readme

Wingnut

A node.js library to build express.js APIs using OpenAPI V3 specs for validation and documentation.

npm version codecov

Installation

Install wingnut using npm i wingnut, or pnpm i wingnut, or yarn i wingnut.

Dependencies

  1. Express.js - npm i express
  2. Ajv - npm i ajv

Usage

import express, { Express, Router, Request, Response } from "express";
import Ajv from "ajv";

import { wingnut, queryParam, getMethod, path, ParamSchema } from "wingnut";

const ajv = new Ajv();

const { route, paths, controller } = wingnut(ajv);

const app: Express = express();

const logListHandler = (_req: Request, res: Response) => {
  res.status(200).json({
    logs: ["log1", "log2"],
  });
};

const logResponseSchema: ParamSchema = {
  type: "object",
  properties: {
    logs: {
      type: "array",
      items: {
        type: "string",
      },
    },
  },
};

const logListController = getMethod({
  tags: ["logs"],
  description: "List all logs",
  parameters: [
    // query parameter validation
    queryParam({
      name: "limit",
      description: "Number of logs to return",
      schema: {
        type: "integer",
        minimum: 1,
        maximum: 100,
      },
    }),
  ],
  middleware: [logListHandler],
  responses: {
    200: {
      description: "Logs",
      content: {
        "application/json": {
          schema: logResponseSchema,
        },
      },
    },
  },
});

// similar to app.use(apis)
paths(
  app,
  controller({
    // map the above handler to /api/logs
    prefix: "/api/logs",
    route: (router: Router) => route(router, path("/", logListController)),
  }),
);

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

Query Params

// Validate `limit` against `req.query`
queryParam({
  name: "limit",
  description: "max number",
  schema: {
    type: "integer",
    minimum: 1,
  },
});

Request Body Validation

// Validate `body` against `req.body`
postMethod({
  requestBody: {
    description: "Create a log entry",
    content: {
      "application/json": {
        schema: {
          type: "object",
          properties: {
            log: {
              type: "object",
              properties: {
                message: {
                  type: "string",
                },
              },
              required: ["message"],
            },
          },
          required: ["log"],
        },
      },
    },
  },
});

Path Param Validation

// Validate `id` against `req.params`
pathParam({
  name: "id",
  description: "log id",
  schema: {
    type: "string",
    format: "uuid",
  },
});

Secure Routes with Scopes

import { scope, Security, authPathOp, ScopeHandler } from "wingnut";

// Build a scope handler to evaluate the user context (session)
const userLevelAuth =
  (minLevel: number): ScopeHandler =>
  (req: UserAuth): boolean =>
    (req.user?.level ?? 0) >= minLevel;

// Build Authorization Security object
const auth: Security = {
  name: "user level authorization",
  // handler if user is not authenticated
  handler: (_req: Request, res: Response, next: NextFunction) => {
    res.status(400).send("Not Authorized");
  },
  scopes: {
    // define OpenAPI security scopes based on user levels
    // these can be referenced with wingunut's Scope
    admin: userLeveltAuth(100),
    user: userLevelAuth(10),
  },
  // response schema for authorization failure
  responses: {
    "400": {
      description: "Not Authorized",
    },
  },
};

// reusable scope handler to secure admin-only routes
const adminAuth = authPathOp(Scope(auth, "admin"));

// possible user update schema
const updateUserSchema = {
  type: "object",
  properties: {
    user: {
      type: "object",
      properties: {
        level: {
          type: "integer",
          minimum: 0,
        },
      },
      required: ["level"],
    },
  },
  required: ["user"],
};

// perform authorization using AdminAuth before updating
const editUserAPI = adminAuth(
  putMethod({
    description: "Edit a user",
    requestBody: {
      description: "user attributes to edit",
      content: {
        "application/json": {
          schema: updateUserSchema,
        },
      },
    },
    middleware: [
      // express.js RequestHandler requires admin authentication now
    ],
  }),
);

Type-Safe Request Values

import { WnParamDef, WnDataType } from "wingnut";

const ListQueryParams = {
  properties: {
    limit: {
      description: "Number of logs to return",
      schema: {
        type: "integer",
        minimum: 1,
        maximum: 100,
        format: "number",
        default: 10,
      },
    },
    filter: {
      description: "Filter logs by message",
      schema: {
        type: "string",
        nullable: true,
      },
    },
  },
} satisfies WnParamDef;

type ListRequest = Request<
  unknown,
  unknown,
  unknown,
  WnDataType<typeof ListQueryParams>
>;

// Request Handler
const listLogsHandler = (
  req: ListRequest,
  res: Response,
  next: NextFunction,
) => {
  // limit and filter are correctly typed
  const { limit, filter } = req.query;
  // ...
};

Swagger Documentation

import express from 'express';
import Ajv from 'ajv';
import { PathItem, wingnut } from 'wingunut';
import swaggerUI from 'swagger-ui-express';

const ajv = new Ajv();
ajv.opts.coerceTypes = true;

// base swagger document
const swaggerPath = (paths: PathItem) => ({
  openapi: '3.0.0',
  info: {
    version: '1.0.0',
    title: 'My App Swagger Doc',
    description: 'My App Swagger Doc',
  },
  paths;
})

const { route, paths, controller } = wingnut(ajv)

const app = express()

export const apis = (app: Express) => {
  const openApiPaths = paths(
    app,
    controller({
      // map the above handler to /api/logs
    })
  )
  // map all paths within the swagger documentation
  const swaggerDoc = swaggerPath(openApiPaths)
  // serve swagger documentation at /api-docs
  app.use('/api-docs', swaggerUI.serve, swaggerUI.setup(swaggerDoc))
}

// app.ts
apis(app)
app.listen(3000)