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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@e22m4u/js-openapi

v0.0.5

Published

JavaScript модуль для создания OpenAPI Документа

Readme

@e22m4u/js-openapi

JavaScript модуль для создания OpenAPI Документа 3.1.0

Содержание

Установка

npm install @e22m4u/js-openapi

Модуль поддерживает ESM и CommonJS стандарты.

ESM

import {OADocumentBuilder} from '@e22m4u/js-openapi';

CommonJS

const {OADocumentBuilder} = require('@e22m4u/js-openapi');

Базовый пример

Создание экземпляра сборщика.

import {OADocumentBuilder} from '@e22m4u/js-openapi';

const builder = new OADocumentBuilder({
  info: {
    title: 'My Simple API',
    version: '0.0.1',
  },
});

Определение операции.

import {OAOperationMethod} from '@e22m4u/js-openapi';

builder.defineOperation({
  path: '/status',
  method: OAOperationMethod.GET,
  operation: {
    summary: 'Get server status',
    responses: {
      200: {
        description: 'Server works fine',
      },
    },
  },
});

Формирование JSON документа.

const jsonDoc = builder.buildJson(2);
// первый аргумент указывает количество пробелов
// для каждого уровня вложенности, и может быть
// опущен в целях экономии размера документа

console.log(jsonDoc);
// {
//   "openapi": "3.1.0",
//   "info": {
//     "title": "My Simple API",
//     "version": "0.0.1"
//   },
//   "paths": {
//     "/status": {
//       "get": {
//         "summary": "Get server status",
//         "responses": {
//           "200": {
//             "description": "Server works fine"
//           }
//         }
//       }
//     }
//   }
// }

Работа с компонентами

Регистрация компонента схемы.

import {OADataType, OAOperationMethod} from '@e22m4u/js-openapi';

builder.defineSchemaComponent({
  name: 'User', // <= имя нового компонента
  schema: {
    type: OADataType.OBJECT,
    properties: {
      id: {
        type: OADataType.STRING,
        format: 'uuid',
      },
      email: {
        type: OADataType.STRING,
        format: 'email',
      },
    },
    required: ['id', 'email'],
  },
});

Регистрация компонента параметра.

import {OADataType, OAParameterLocation} from '@e22m4u/js-openapi';

builder.defineParameterComponent({
  name: 'idParam', // <= имя нового компонента
  parameter: {
    name: 'id',
    in: OAParameterLocation.PATH,
    description: 'Identifier',
    required: true,
  },
});

Использование зарегистрированного имени компонента.

import {
  oaSchemaRef,
  OAMediaType,
  oaParameterRef,
  OAOperationMethod,
} from '@e22m4u/js-openapi';

// GET /users/{id}
builder.defineOperation({
  path: '/users/{id}',
  method: OAOperationMethod.GET,
  operation: {
    parameters: [
      oaParameterRef('idParam'), // <= ссылка на параметр
      // утилита "oaParameterRef" создаст объект-ссылку:
      // {"$ref": "#/components/parameters/idParam"}
    ],
    responses: {
      200: {
        description: 'User found',
        content: {
          [OAMediaType.APPLICATION_JSON]: {
            schema: oaSchemaRef('User'), // <= ссылка на схему
            // утилита "oaSchemaRef" создаст объект-ссылку:
            // {"$ref": "#/components/schemas/User"}
          },
        },
      },
    },
  },
});

Содержимое запросов и ответов

Определение тела запроса для операции.

import {OADataType, OAMediaType, OAOperationMethod} from '@e22m4u/js-openapi';

// POST /users
builder.defineOperation({
  path: '/users',
  method: OAOperationMethod.POST,
  operation: {
    summary: 'Create a new user',
    // тело запроса
    requestBody: {
      description: 'Data for the new user',
      required: true,
      content: {
        [OAMediaType.APPLICATION_JSON]: {
          // схема тела
          schema: {
            type: OADataType.OBJECT,
            properties: {
              email: {
                type: OADataType.STRING,
                format: 'email',
              },
              password: {
                type: OADataType.STRING,
              },
            },
            required: ['email', 'password'],
          },
        },
      },
    },
  },
});

Определение тела ответа для операции.

import {OADataType, OAMediaType, OAOperationMethod} from '@e22m4u/js-openapi';

// GET /status
builder.defineOperation({
  path: '/status',
  method: OAOperationMethod.GET,
  operation: {
    summary: 'Get server status',
    responses: {
      // успешный ответ
      200: {
        description: 'Server works fine',
        content: {
          [OAMediaType.APPLICATION_JSON]: {
            // схема ответа
            schema: {
              type: OADataType.OBJECT,
              properties: {
                status: {
                  type: OADataType.STRING,
                  example: 'ok',
                },
              },
            },
          },
        },
      },
    },
  },
});

Определение компонента схемы для использования в следующем примере.

import {OADataType} from '@e22m4u/js-openapi';

builder.defineSchemaComponent({
  name: 'UserInput', // <= имя нового компонента
  schema: {
    type: OADataType.OBJECT,
    properties: {
      email: {
        type: OADataType.STRING,
        format: 'email',
      },
      password: {
        type: OADataType.STRING,
      },
    },
    required: ['email', 'password'],
  },
});

Определение содержания запроса и ответа с использованием ссылок.

import {oaSchemaRef, OAMediaType, OAOperationMethod} from '@e22m4u/js-openapi';

// POST /users
builder.defineOperation({
  path: '/users',
  method: OAOperationMethod.POST,
  operation: {
    summary: 'Create a new user',
    // тело запроса
    requestBody: {
      description: 'Data for the new user',
      required: true,
      content: {
        [OAMediaType.APPLICATION_JSON]: {
          schema: oaSchemaRef('UserInput'), // <= ссылка на схему
        },
      },
    },
    responses: {
      // успешный ответ
      201: {
        description: 'User created',
        content: {
          [OAMediaType.APPLICATION_JSON]: {
            schema: oaSchemaRef('User'), // <= ссылка на схему
          },
        },
      },
    },
  },
});

Группировка маршрутов

Создание области с общим префиксом пути и тегом.

import {OAOperationMethod} from '@e22m4u/js-openapi';

// создание области /users
const usersScope = builder.createScope({
  pathPrefix: '/users',
  tags: ['User'], // опционально
});

// маршрут GET /users/{id}
usersScope.defineOperation({
  path: '/{id}',
  method: OAOperationMethod.GET,
  operation: {
    summary: 'Find user',
    responses: {
      200: {
        description: 'User found',
      },
    },
  },
});

// маршрут DELETE /users/{id}
usersScope.defineOperation({
  path: '/{id}',
  method: OAOperationMethod.DELETE,
  operation: {
    summary: 'Delete user',
    responses: {
      200: {
        description: 'User deleted',
      },
    },
  },
});

Создание вложенных областей для комбинирования маршрутов.

import {OAOperationMethod} from '@e22m4u/js-openapi';

// область "/api/v1"
const v1Scope = builder.createScope({
  pathPrefix: '/api/v1',
});

// область "/api/v1/admin"
const adminScope = v1Scope.createScope({
  pathPrefix: '/admin',
});

// DELETE /api/v1/admin/users/{id}
adminScope.defineOperation({
  path: '/users/{id}',
  method: OAOperationMethod.DELETE,
  operation: {
    summary: 'Delete user',
    responses: {
      200: {
        description: 'User deleted',
      },
    },
  },
});

Проверка данных

Проверка данных с помощью объекта схемы.

import {OADataType, validateDataWithOpenApiSchema} from '@e22m4u/js-openapi';

const schema = {
  type: OADataType.OBJECT,
  properties: {
    name: {type: OADataType.STRING},
    age: {type: OADataType.NUMBER},
  },
};

const data = {
  name: 'Fedor',
  age: 'invalid',
};

validateDataWithOpenApiSchema(data, schema);
// OADataValidationError:
// Value at "/age" must be Number, but String was given.

Отключение выброса ошибки для ручной обработки результата.

const result = validateDataWithOpenApiSchema(data, schema, {
  silent: true, // <= бесшумный режим
});
console.log(result);
// {
//   isValid: false,
//   value: 'invalid',
//   valueUri: '/age',
//   schemaUri: '/properties/age',
//   reason: 'Value at "/age" must be Number, but String was given.',
// }

Проверка данных с приведением типов.

import {OADataType, validateDataWithOpenApiSchema} from '@e22m4u/js-openapi';

const schema = {
  type: OADataType.OBJECT,
  properties: {
    phone: {type: OADataType.STRING},
    quantity: {type: OADataType.INTEGER},
    featured: {type: OADataType.BOOLEAN},
  },
};

const data = {
  phone: 88005553535, // приводится к строке
  quantity: '3',      // приводится к целому числу
  featured: 'true'    // приводится к логическому значению
};

const result = validateDataWithOpenApiSchema(data, schema, {
  coerceTypes: true, // <= приведение типов
});
console.log(result);
// {
//   isValid: true,
//   value: {
//     phone: '88005553535',
//     quantity: 3,
//     featured: true
//   }
// }

Проверка данных с разбором JSON.

import {OADataType, validateDataWithOpenApiSchema} from '@e22m4u/js-openapi';

const schema = {
  type: OADataType.ARRAY,
  prefixItems: [
    {type: OADataType.INTEGER},
    {type: OADataType.BOOLEAN},
    {type: OADataType.ARRAY},
    {type: OADataType.OBJECT},
  ],
};

const data = [
  '123',       // приводится к целому числу
  'true',      // приводится к логическому значению
  '[1, 2, 3]', // приводится к массиву
  '{"where": {"id": 10}, "include": "user"}', // приводится к объекту
];

const result = validateDataWithOpenApiSchema(data, schema, {
  parseJson: true, // <= разбор JSON
});
console.log(result);
// {
//   isValid: true,
//   value: [
//     123,
//     true,
//     [1, 2, 3],
//     {
//       where: {
//         id: 10,
//       },
//       include: 'user'
//     }
//   ]
// }

Тесты

npm run test

Лицензия

MIT