diff --git a/README.md b/README.md index f0cf59b..c20d0bf 100644 --- a/README.md +++ b/README.md @@ -11,11 +11,40 @@ Use [@apidevtools/json-schema-ref-parser](https://github.com/APIDevTools/json-sc Use [openapi-snippet](https://github.com/ErikWittern/openapi-snippet) to generate code samples automatically. -### Convert string to int for int32 type in `.proto` - -ToDo - -### Import markown files +### Convert the example and default values of integer type to int + +A `int32` type `port` defined in the `.proto` file is: + +```proto +int32 port = 1 [(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = { + format: "int32", + default: "8080", + example: "8080" +``` + +The default JSON generated by `bufbuild/buf` is: + +```json +"port": { + "type": "integer", + "format": "int32", + "example": 8080, + "default": "8080" +} +``` + +`replaceint.js` replaces all integer values and the processed JSON file is: + +```json +"port": { + "type": "integer", + "format": "int32", + "example": 8080, + "default": 8080 +} +``` + +### Import markdown files Embed external Markdown file contents to the `info.description` auto-generated JSON file. See [Redoc documentation](https://redocly.com/docs/api-reference-docs/guides/embedded-markdown/) for more information. diff --git a/src/main.js b/src/main.js index f80c238..f392d43 100644 --- a/src/main.js +++ b/src/main.js @@ -5,6 +5,7 @@ const importMd = require("./importmd.js"); const addLogo = require("./addlogo.js"); const genSampleCode = require("./gencode.js"); const devTier = require("./devTier.js"); +const replaceInteger = require("./replaceint.js"); const program = new Command(); program @@ -37,4 +38,9 @@ program.command("devtier") .description("Add sample for creating a dev tier cluster") .argument("", "Input JSON file") + .argument("[out-filename]", "Output JSON file. If not specified, use in-filename.") + .action(replaceInteger); program.parse(); diff --git a/src/replaceint.js b/src/replaceint.js new file mode 100644 index 0000000..7720eaa --- /dev/null +++ b/src/replaceint.js @@ -0,0 +1,28 @@ +const fs = require("fs"); + +function replaceIntegerInternal(obj) { + for (let item in obj) { + if (obj[item] instanceof Object) { + replaceIntegerInternal(obj[item]); + } + else if (item == "type" && obj[item] === "integer") { + if (obj["example"] != undefined && typeof obj["example"] != "number") { + obj["example"] = parseInt(obj["example"]); + } + if (obj["default"] != undefined && typeof obj["default"] != "number") { + obj["default"] = parseInt(obj["default"]); + } + } + } + return obj; +} + +async function replaceInteger(readf, writef) { + writef = writef || readf; + const data = JSON.parse(fs.readFileSync(readf, 'utf8')); + const schema = replaceIntegerInternal(data); + fs.writeFileSync(writef, JSON.stringify(schema, null, 2)); + console.log(`Replace wrong string with int in ${writef}`); +} + +module.exports = replaceInteger;