Skip to content

Commit 1c2bf61

Browse files
committed
feat(sample-gen): yaml sample generation
if content / media type matches yaml or yml it will generate stringified sample like for json in addition to that it will generate yaml out of the json sample Signed-off-by: mathis-m <[email protected]>
1 parent ab0cdbf commit 1c2bf61

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/core/utils.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import cssEscape from "css.escape"
2525
import getParameterSchema from "../helpers/get-parameter-schema"
2626
import randomBytes from "randombytes"
2727
import shaJs from "sha.js"
28+
import YAML from "js-yaml"
2829

2930

3031
const DEFAULT_RESPONSE_KEY = "default"
@@ -581,6 +582,21 @@ const getStringifiedSampleForSchema = (schema, config, contentType, exampleOverr
581582
: res
582583
}
583584

585+
const getYamlSampleSchema = (schema, config, contentType, exampleOverride) => {
586+
const jsonExample = getStringifiedSampleForSchema(schema, config, contentType, exampleOverride)
587+
let yamlString
588+
try {
589+
yamlString = YAML.safeDump(YAML.safeLoad(jsonExample), {
590+
lineWidth: -1 // don't generate line folds
591+
})
592+
} catch (e) {
593+
console.error(e)
594+
return "error: could not generate yaml example"
595+
}
596+
return yamlString
597+
.replace(/\t/g, " ")
598+
}
599+
584600
export const getSampleSchema = (schema, contentType="", config={}, exampleOverride = undefined) => {
585601
if(schema && isFunc(schema.toJS))
586602
schema = schema.toJS()
@@ -590,7 +606,9 @@ export const getSampleSchema = (schema, contentType="", config={}, exampleOverri
590606
if (/xml/.test(contentType)) {
591607
return getXmlSampleSchema(schema, config, exampleOverride)
592608
}
593-
609+
if (/(yaml|yml)/.test(contentType)) {
610+
return getYamlSampleSchema(schema, config, contentType, exampleOverride)
611+
}
594612
return getStringifiedSampleForSchema(schema, config, contentType, exampleOverride)
595613
}
596614

0 commit comments

Comments
 (0)