ajv-to-swagger

1.0.3 • Public • Published

ajv-to-swagger

Convert schema from AJV to Swagger

npm license Build Status dependencies Status devDependencies Status Coverage Status Known Vulnerabilities

That package converts ajv schemas (JSON schema draft 07) to Swagger schema (OpenApi 3).

All you need to do after conversion is to insert converted schema into corresponding place in swagger schema.

Install

npm i ajv-to-swagger

Usage

const convertor = require('ajv-to-swagger');
 
// some kind of AJV schema which we provide as a response
const ajvResponseSchema = {
  type: 'object',
  properties: {
    currency: { type: 'string', minLength: 3, maxLength: 3 },
    id: { type: 'string', minLength: 36, maxLength: 36 },
    version: { enum: [2] },
    rates: {
      type: 'object',
      example: {
        USDEUR: '0.881367883',
        USDRUB: '67.905200000'
        },
      patternProperties: {
        '^[A-Z]{6}$': { type: 'string' },
      },
      additionalProperties: false,
    },
  },
  additionalProperties: false,
};
  
// make a draft of your schema without a response schema:
const baseSchema = 
    {
      "openapi": "3.0.1",
      "info": {
        "title": "defaultTitle",
        "description": "defaultDescription",
        "version": "0.1"
      },
      "servers": [
        {
          "url": "https://google.com"
        }
      ],
      "paths": {
        "/get/some/": {
          "get": {
            "description": "Auto generated using Swagger Inspector",
            "parameters": [
              {
                "name": "cs",
                "in": "query",
                "schema": {
                  "type": "string"
                },
                "example": "E"
              }
            ],
            "responses": {
              "200": {
                "description": "Auto generated using Swagger Inspector",
                "content": {
                  "application/json": {
                    "schema": {}
                  }
                }
              }
            },
            "servers": [
              {
                "url": "https://google.com"
              }
            ]
          },
          "servers": [
            {
              "url": "https://google.com"
            }
          ]
        }
      }
    };
 
const responseSwagger = convertor.convertSchema(ajvResponseSchema);
 
// put your schema where it needs to be
baseSchema.paths['/get/some/'].get.responses['200'].content['application/json'].schema = responseSwagger.schema;

Now swaggerDoc has a valid Swagger schema. You can serialize it in JSON and ouput when needed.

Limitations

Currently ajv-to-swagger does not support many patternProperties, only one. But it is usually enough.

Readme

Keywords

Package Sidebar

Install

npm i ajv-to-swagger

Weekly Downloads

8

Version

1.0.3

License

MIT

Unpacked Size

8.58 kB

Total Files

4

Last publish

Collaborators

  • bollwar404