-
Notifications
You must be signed in to change notification settings - Fork 167
/
generate-swagger.js
95 lines (75 loc) · 1.83 KB
/
generate-swagger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#! /usr/bin/env node
'use strict'
const parseArgs = require('./args')
const argv = require('yargs-parser')
const log = require('./log')
const {
exit,
requireFastifyForModule,
requireServerPluginFromPath,
showHelpForCommand
} = require('./util')
const fp = require('fastify-plugin')
let Fastify = null
function loadModules (opts) {
try {
Fastify = requireFastifyForModule(opts._[0]).module
} catch (e) {
module.exports.stop(e)
}
}
async function generateSwagger (args) {
const opts = parseArgs(args)
const extraOpts = argv(args)
if (opts.help) {
return showHelpForCommand('generate-swagger')
}
if (opts._.length !== 1) {
console.error('Missing the required file parameter\n')
return showHelpForCommand('generate-swagger')
}
loadModules(opts)
const fastify = await runFastify(opts)
try {
if (fastify.swagger == null) {
log('error', '@fastify/swagger plugin not installed')
process.exit(1)
}
if (extraOpts.yaml) {
return fastify.swagger({ yaml: true })
} else {
return JSON.stringify(fastify.swagger(), undefined, 2)
}
} finally {
fastify.close()
}
}
async function runFastify (opts) {
require('dotenv').config()
let file = null
try {
file = await requireServerPluginFromPath(opts._[0])
} catch (e) {
return module.exports.stop(e)
}
const fastify = Fastify(opts.options)
const pluginOptions = {}
if (opts.prefix) {
pluginOptions.prefix = opts.prefix
}
await fastify.register(fp(file), pluginOptions)
await fastify.ready()
return fastify
}
function stop (message) {
exit(message)
}
function cli (args) {
return generateSwagger(args).then(swagger => {
process.stdout.write(swagger + '\n')
})
}
module.exports = { cli, stop, generateSwagger }
if (require.main === module) {
cli(process.argv.slice(2))
}