Модуль OpenAPI документации для @e22m4u/js-trie-router

e22m4u b256b8e4cf chore: initial commit 4 дней назад
.husky b256b8e4cf chore: initial commit 4 дней назад
src b256b8e4cf chore: initial commit 4 дней назад
.c8rc b256b8e4cf chore: initial commit 4 дней назад
.commitlintrc b256b8e4cf chore: initial commit 4 дней назад
.editorconfig b256b8e4cf chore: initial commit 4 дней назад
.gitignore b256b8e4cf chore: initial commit 4 дней назад
.mocharc.json b256b8e4cf chore: initial commit 4 дней назад
.prettierrc b256b8e4cf chore: initial commit 4 дней назад
LICENSE b256b8e4cf chore: initial commit 4 дней назад
README.md b256b8e4cf chore: initial commit 4 дней назад
build-cjs.js b256b8e4cf chore: initial commit 4 дней назад
eslint.config.js b256b8e4cf chore: initial commit 4 дней назад
package.json b256b8e4cf chore: initial commit 4 дней назад
tsconfig.json b256b8e4cf chore: initial commit 4 дней назад

README.md

@e22m4u/js-trie-router-openapi

Модуль OpenAPI документации для @e22m4u/js-trie-router

Содержание

Установка

npm install @e22m4u/js-trie-router-openapi

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

ESM

import {TrieRouterOpenApi} from '@e22m4u/js-trie-router-openapi';

CommonJS

const {TrieRouterOpenApi} = require('@e22m4u/js-trie-router-openapi');

Использование

Подключение модуля к маршрутизатору.

import {TrieRouter} from '@e22m4u/js-trie-router';
import {TrieRouterOpenApi} from '@e22m4u/js-trie-router-openapi';

// создание маршрутизатора
const router = new TrieRouter();

// подключение расширения
router.useService(TrieRouterOpenApi, {
  info: {
    title: 'API Documentation',
    version: '0.0.1',
  },
});

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

import {OADataType, OADocumentBuilder} from '@e22m4u/js-trie-router-openapi';

const builder = router.getService(OADocumentBuilder);

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

// публичные данные пользователя
builder.defineSchemaComponent({
  name: 'UserOutput', // <= имя новой схемы
  schema: {
    type: OADataType.OBJECT,
    properties: {
      id: {
        type: OADataType.STRING,
        format: 'uuid',
      },
      email: {
        type: OADataType.STRING,
        format: 'email',
      },
    },
    required: ['id', 'password'],
  },
});

Определение метаданных маршрута.

import {HttpMethod} from '@e22m4u/js-trie-router';
import {oaSchemaRef, OAMediaType} from '@e22m4u/js-trie-router-openapi';

router.defineRoute({
  method: HttpMethod.POST,
  path: '/users',
  meta: {
    openApi: {
      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('UserOutput'),
              // ссылка на схему ^^^
            },
          },
        },
      },
    },
  },
  handler: (ctx) => {
    // ...
  },
});

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

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

const builder = router.getService(OADocumentBuilder);

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

console.log(jsonDoc);
// {
//   "openapi": "3.1.0",
//   "info": {
//     "title": "API Documentation",
//     "version": "0.0.1"
//   },
//   "paths": {
//     "/users": {
//       "post": {
//         "summary": "Create a new user",
//         "requestBody": {
//           "description": "Data for the new user",
//           "required": true,
//           "content": {
//             "application/json": {
//               "schema": {
//                 "$ref": "#/components/schemas/UserInput"
//               }
//             }
//           }
//         },
//         "responses": {
//           "201": {
//             "description": "User created",
//             "content": {
//               "application/json": {
//                 "schema": {
//                   "$ref": "#/components/schemas/UserOutput"
//                 }
//               }
//             }
//           }
//         }
//       }
//     }
//   },
//   "components": {
//     "schemas": {
//       "UserInput": { ... },
//       "UserOutput": { ... }
//     }
//   }
// }

Тесты

npm run test

Лицензия

MIT