Skip to content

Commit e37c737

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 e37c737

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/core/utils.js

Lines changed: 23 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,25 @@ 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+
591+
lineWidth: -1 // don't generate line folds
592+
})
593+
if(yamlString[yamlString.length - 1] === "\n") {
594+
yamlString = yamlString.slice(0, yamlString.length - 1)
595+
}
596+
} catch (e) {
597+
console.error(e)
598+
return "error: could not generate yaml example"
599+
}
600+
return yamlString
601+
.replace(/\t/g, " ")
602+
}
603+
584604
export const getSampleSchema = (schema, contentType="", config={}, exampleOverride = undefined) => {
585605
if(schema && isFunc(schema.toJS))
586606
schema = schema.toJS()
@@ -590,7 +610,9 @@ export const getSampleSchema = (schema, contentType="", config={}, exampleOverri
590610
if (/xml/.test(contentType)) {
591611
return getXmlSampleSchema(schema, config, exampleOverride)
592612
}
593-
613+
if (/(yaml|yml)/.test(contentType)) {
614+
return getYamlSampleSchema(schema, config, contentType, exampleOverride)
615+
}
594616
return getStringifiedSampleForSchema(schema, config, contentType, exampleOverride)
595617
}
596618

0 commit comments

Comments
 (0)