Closed2

【OpenAPI】ymlファイルから$refを取り除き、allOfを展開してjsonファイル出力したい

やむ | serinaやむ | serina

実行ファイルの書き方(js)

main.js
const SwaggerParser = require('@apidevtools/swagger-parser');
const mergeAllOf = require('json-schema-merge-allof');
const fs = require('fs');

/**
 * $refを取り除き、allOfを展開してファイル出力
 * @param {*} inputFilePath 
 * @param {*} outputFilePath 
 */
async function processOpenAPISchema(inputFilePath, outputFilePath) {
  try {
    // OpenAPI仕様をデリファレンス
    const api = await SwaggerParser.dereference(inputFilePath);

    // allOfを展開し、順序を保ったスキーマを作成する関数
    function processSchema(schema) {
      if (schema && typeof schema === 'object') {
        if (schema.allOf) {
          schema = mergeAllOf(schema, { resolvers: {} });
        }
        for (const key in schema) {
          schema[key] = processSchema(schema[key]);
        }
        if (schema.type === 'object') {
          return {
            type: schema.type,
            properties: schema.properties,
            required: schema.required,
          };
        }
      }
      return schema;
    }

    // デリファレンスされたAPI全体を処理
    const processedApi = processSchema(api);

    // 結果をファイルに書き出す
    fs.writeFileSync(outputFilePath, JSON.stringify(processedApi, null, 2));
    console.log('Processed OpenAPI schema written to', outputFilePath);
  } catch (err) {
    console.error('Error processing OpenAPI schema:', err);
  }
}

processOpenAPISchema('index.yml', 'openapi-without-allOf-and-ref.json');

実行方法

node main.js

ライブラリ(GitHubリポジトリ)

https://github.com/APIDevTools/swagger-parser

https://github.com/mokkabonna/json-schema-merge-allof

このスクラップは2024/08/30にクローズされました