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

@moontai0724/openapi

v1.1.1

Published

An OpenAPI document define, generate and schema validation library supported by ajv.

Downloads

11

Readme

@moontai0724/openapi

NPM Version NPM Downloads Codecov

An OpenAPI document define, generate and schema validation library supported by ajv.

📝 Table of Contents

Install

NPM

npm install @moontai0724/openapi

Yarn

yarn add @moontai0724/openapi

PNPM

pnpm add @moontai0724/openapi

Usage

define(path, method, schemas, options)

You can define a path by calling the define method.

import OpenAPI, {
  type OperationSchemas,
  type TransformPathItemOptions,
} from "@moontai0724/openapi";
import Type from "@sinclair/typebox";

const openapi = new OpenAPI({
  /** basic document options */
});

const path = "/:path1";
const method = "patch";
const schemas: OperationSchemas = {
  body: Type.Object({
    body1: Type.String(),
  }),
  cookie: Type.Object({
    cookie1: Type.String(),
  }),
  header: Type.Object({
    header1: Type.String(),
  }),
  path: Type.Object({
    path1: Type.String(),
  }),
  query: Type.Object({
    query1: Type.String(),
  }),
  response: Type.Object({
    response1: Type.String(),
  }),
};
const options: TransformPathItemOptions = {
  /** options */
};

openapi.define(path, method, schemas, options);

For more informations, you can see examples below or the API documentation.

init(path, method, schemas, options)

You can get the Ajv instance for further validation when initializing the OpenAPI instance by calling the init method.

import OpenAPI from "@moontai0724/openapi";

const openapi = new OpenAPI({
  /** basic document options */
});

const path = "/:id";
const method = "patch";
const schemas: OperationSchemas = {
  cookie: {
    type: "object",
    properties: {
      token: {
        type: "string",
        description: "Token",
      },
    },
  },
  path: {
    type: "object",
    required: ["id"],
    properties: {
      id: {
        type: "number",
      },
    },
  },
  response: {
    description: "Specific resource",
    type: "object",
    required: ["success", "message"],
    properties: {
      success: {
        type: "boolean",
      },
      message: {
        type: "string",
      },
    },
  },
};
const options: TransformPathItemOptions = {
  /** options */
};

const ajv = openapi.init(path, method, schemas, options); // got the Ajv instance with schemas defined

For more informations, you can see examples below or the API documentation.

validate(path, method, data, options)

You can validate a set of data after defined a path by calling the validate method.

import OpenAPI from "@moontai0724/openapi";

const openapi = new OpenAPI({
  /** basic document options */
});

const path = "/:id";
const method = "patch";
const schemas: OperationSchemas = {
  /** schemas same as above */
};

openapi.define(path, method, schemas);

const data = {
  body: {
    body1: "body1",
  },
  cookie: {
    cookie1: "cookie1",
  },
  header: {},
  path: null,
  query: undefined,
};

const result = openapi.validate(path, method, data);
/**
 * result = {
 *   body: null,
 *   cookie: null,
 *   header: [
 *     {
 *       instancePath: "",
 *       keyword: "required",
 *       message: "must have required property 'header1'",
 *       params: {
 *         missingProperty: "header1",
 *       },
 *       schemaPath: "#/required",
 *     },
 *   ],
 *   path: [
 *     {
 *       instancePath: "",
 *       keyword: "type",
 *       message: "must be object",
 *       params: {
 *         type: "object",
 *       },
 *       schemaPath: "#/type",
 *     },
 *   ],
 *   query: [
 *     {
 *       instancePath: "",
 *       keyword: "type",
 *       message: "must be object",
 *       params: {
 *         type: "object",
 *       },
 *       schemaPath: "#/type",
 *     },
 *   ],
 * }
 */

For more informations, you can see the API documentation.

Examples

Define a path and generate the document

import OpenAPI from "@moontai0724/openapi";

const openapi = new OpenAPI({
  openapi: "3.1.0",
  info: {
    title: "Example",
    version: "1.0.0",
  },
});

openapi.define("/:id", "get", {
  cookie: {
    type: "object",
    properties: {
      token: {
        type: "string",
        description: "Token",
      },
    },
  },
  path: {
    type: "object",
    required: ["id"],
    properties: {
      id: {
        type: "number",
      },
    },
  },
  response: {
    description: "Specific resource",
    type: "object",
    required: ["success", "message"],
    properties: {
      success: {
        type: "boolean",
      },
      message: {
        type: "string",
      },
    },
  },
});

console.log(openapi.json()); // Generated OpenAPI JSON string.
console.log(openapi.yaml()); // Generated OpenAPI YAML string.

Rather than directly defining the JSON schemas in hand, we recommend you to use the TypeBox library to define the schemas. It would be like this:

import { Type } from "@sinclair/typebox";

import OpenAPI from "./src";

const openapi = new OpenAPI({
  openapi: "3.1.0",
  info: {
    title: "Example",
    version: "1.0.0",
  },
});

openapi.define("/:id", "get", {
  cookie: Type.Object({
    token: Type.Optional(
      Type.String({
        description: "Token",
      }),
    ),
  }),
  path: Type.Object({
    id: Type.Number(),
  }),
  response: Type.Object(
    {
      success: Type.Boolean(),
      message: Type.String(),
    },
    { description: "Specific resource" },
  ),
});

console.log(openapi.json()); // Generated OpenAPI JSON string.
console.log(openapi.yaml()); // Generated OpenAPI YAML string.

The above code will generate the following document:

openapi: "3.1.0"
info:
  title: "Example"
  version: "1.0.0"
paths:
  /:id:
    get:
      parameters:
        - name: "token"
          in: "cookie"
          description: "Token"
          required: false
          schema:
            type: "string"
        - name: "id"
          in: "path"
          required: true
          schema:
            type: "number"
      responses:
        200:
          description: "Specific resource"
          content:
            application/json:
              schema:
                type: "object"
                properties:
                  success:
                    type: "boolean"
                  message:
                    type: "string"
                required:
                  - "success"
                  - "message"

Define a path and generate the document with options to adjust or overwrites

The last parameter is options for transforming the schemas.

There are some options when transforming the schema and also overwrites to the transformed schema.

For example, you can change the response http code or apply schema to specific content types:

/* ... */
openapi.define(
  "/",
  "post",
  {
    body: {
      type: "object",
      properties: {
        name: {
          type: "string",
        },
      },
    },
  },
  {
    requestBody: {
      contentTypes: ["application/json", "application/x-www-form-urlencoded"],
    },
    responses: {
      httpCode: 201,
      overwrite: {
        default: {
          description: "Default Empty Response",
        },
      },
    },
  },
);
/* ... */

The above code will generate the following document:

openapi: "3.1.0"
info:
  title: "Example"
  version: "1.0.0"
paths:
  /:
    post:
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: "object"
              properties:
                name:
                  type: "string"
          application/x-www-form-urlencoded:
            schema:
              type: "object"
              properties:
                name:
                  type: "string"
      responses:
        201:
          description: "No Description." # Since the description is required in response, there will set "No Description." if schema has no description.
        default:
          description: "Default Empty Response"

API Document

For more informations, you can see the API documentation.