Summary
- expressに記述している複数のルーティングを一括でテキストまたはjsonに出力できないか調べてみました。
References
github.com
Example Code
- 下記のコードで記述するとPath及びPathに紐づくメソッド名が取得できる。
router.stack.filter(r => r.route).map(r=> {
return {"path":r.route.path, "methods":r.route.methods}
})
- ExpressのAPI経由でPathとメソッドの情報を取得した場合
router.get('/test', function (req, res) {
res.json({
route: router.stack.filter(r => r.route)
.map(r=> { return {"path":r.route.path,
"methods":r.route.methods}}),
});
})
- Pathとメソッドの情報を取得した情報をswagger.yamlの形式で出力した場合。(swagger.yamlのpaths部分をのみ出力するイメージ。ただし必要最低限のみ)
## 上記のAPIで取得したjsonの値を変数にセットする
const rowJson = "出力したJSON"
const fs = require('fs');
let swggerJson = ''
for (const json of rowJson['route']) {
console.log(json.path)
console.log(Object.keys(json.methods)[0])
const url = json.path
const params = url.split(':')
if (params[1]) {
swggerJson = swggerJson + `
${params[0]}{${params[1].replace(':', '')}}:
${Object.keys(json.methods)[0]}:
summary: テストテストテスト
`
} else {
swggerJson = swggerJson + `
${json.path}:
${Object.keys(json.methods)[0]}:
summary: テストテストテスト
`
}
if (Object.keys(json.methods)[0] === 'post') {
swggerJson = `${swggerJson}
requestBody:
content:
application/json:
schema:
type: object
responses:
"200":
description: ok
`
} else {
if (params[1]) {
swggerJson = `${swggerJson}
parameters:
- name: "${params[1]}"
in: "path"
schema:
type: "integer"
description: "${params[1]}パラメータを取得する"
required: true
responses:
'200':
description: OK
content:
text/plain:
schema:
type: string
`
} else {
swggerJson = `${swggerJson}
responses:
'200':
description: OK
content:
text/plain:
schema:
type: string
`
}
}
}
fs.writeFile('test.txt', swggerJson, function (err: any) {
if (err) { throw err; }
console.log('test.txtが作成されました');
});
Conclusion
- わざわざ自作しせずに自動でexpressで記述したルーティングをswagger.yamlに出力してくれるツールがあると便利だったのですが、自分が探したところでは上手く動作してくれるツールや既存のコードに手を咥えないと使えないライブラリとかしかなかったので、一時的に手動で出力できるコードを書きました。