forked from wework/json-schema-to-openapi-schema
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathjson-schema-to-openapi-schema.js
executable file
·107 lines (95 loc) · 2.39 KB
/
json-schema-to-openapi-schema.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
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env node
'use strict';
const yargs = require('yargs');
const converter = require('../dist/index.js').default;
const helpText = require('./help-text.json');
const fs = require('fs');
const readFileAsync = require('util').promisify(fs.readFile);
(async function main() {
let args = parseArgs();
let command = args.command;
let file = args.file;
let options = args.options;
if (options.help) {
// Show help text and exit
console.log(getHelpText(command));
process.exit(0);
} else if (command === 'convert' && file) {
// Convert the JSON Schema file
await convert(file, options);
} else {
// Invalid args. Show help text and exit with non-zero
console.error('Error: Invalid arguments\n');
console.error(getHelpText(command));
process.exit(1);
}
})();
/**
* Parses the command-line arguments
*
* @returns {object} - The parsed arguments
*/
function parseArgs() {
// Configure the argument parser
yargs
.option('d', {
alias: 'dereference',
type: 'boolean',
default: false,
})
.option('h', {
alias: 'help',
type: 'boolean',
});
// Show the version number on "--version" or "-v"
yargs.version().alias('v', 'version');
// Disable the default "--help" behavior
yargs.help(false);
// Parse the command-line arguments
let args = yargs.argv;
// Normalize the parsed arguments
let parsed = {
command: args._[0],
file: args._[1],
options: {
dereference: args.dereference,
help: args.help,
},
};
return parsed;
}
/**
* Convert an JSON Schema to OpenAPI schema
*
* @param {string} file - The path of the file to convert
* @param {object} options - Conversion options
*/
async function convert(file, options) {
try {
const schema = await readFileAsync(file, 'utf8');
const converted = await converter(JSON.parse(schema), options);
console.log(JSON.stringify(converted));
} catch (error) {
errorHandler(error);
}
}
/**
* Returns the help text for the specified command
*
* @param {string} [commandName] - The command to show help text for
* @returns {string} - the help text
*/
function getHelpText(commandName) {
let lines = helpText[commandName] || helpText.default;
return lines.join('\n');
}
/**
* Writes error information to stderr and exits with a non-zero code
*
* @param {Error} err
*/
function errorHandler(err) {
let errorMessage = process.env.DEBUG ? err.stack : err.message;
console.error(errorMessage);
process.exit(1);
}