LoginSignup
1
0

More than 5 years have passed since last update.

複数に分割したJSONファイルから、swaggerのyamlファイルを生成する

Last updated at Posted at 2018-08-30

yamlファイルが凄く……大きいです……
という状況になってしまって更新が大変になってしまったので。
どうしてこうなるまで放っておいたんだとか、その管理方法は間違ってるよね!と言われればそれまでなんですが……:sob:
こういう方法もあるよね、ということで。

実装例

{
  "swagger": "2.0",
  "info": {
    "description": "create-swagger-yml-from-many-json",
    "version": "1.0.0",
    "title": "create-swagger-yml-from-many-json"
  },
  "host": "localhost",
  "basePath": "/",
  "schemes": [
    "https"
  ],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "paths": {
    "$ref": "./path.json"
  }
}
const fs = require('fs');
const JsonRefs = require('json-refs');
const YAML = require('json2yaml');
const root = require('./sample/index.json');
const options = {
  filter: ['relative', 'remote']
};

const outputPath = process.cwd() + '/swagger.yml';

process.chdir('sample');

JsonRefs.resolveRefs(root, options)
  .then(function (res) {
    fs.writeFileSync(outputPath,
      YAML.stringify(res.resolved)
    );
  }, function (err) {
    console.log(err.stack);
  });

対象のjsonファイルを読み込み、jsonRefsというライブラリで$refの部分を結合させています。
キモはprocess.chdir('sample') です。
$refを探す時にcurretディレクトリをベースに探してしまうので、chdirでcurrentディレクトリを変更してあげます。

結果

---
  swagger: "2.0"
  info: 
    description: "create-swagger-yml-from-many-json"
    version: "1.0.0"
    title: "create-swagger-yml-from-many-json"
  host: "localhost"
  basePath: "/"
  schemes: 
    - "https"
  consumes: 
    - "application/json"
  produces: 
    - "application/json"
  paths: 
    /test_api: 
      get: 
        summary: "TEST API"
        parameters: []
        responses: 
          200: 
            schema: 
              type: "object"
              properties: 
                id: 
                  type: "integer"
                  description: "店舗ID"
                  example: 1
                name: 
                  type: "string"
                  description: "店舗名"
                  example: "店舗!"

mergeした結果ができました!

追記

毎日更新してみようと思ったけれども、ネタ切れが酷い!

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0