Skip to content

Commit 03e31e2

Browse files
Add normalizer to transform const to single-value enum (#5)
1 parent 360a47f commit 03e31e2

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

plugin.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,41 @@ class ConfigSchemaHandlerTypescriptDefinitionsPlugin {
2222
// This definition is causing memory trouble
2323
delete this.schema.properties.provider.properties.s3.additionalProperties.properties.replicationConfiguration
2424

25+
/**
26+
* https://github.com/serverless/typescript/issues/4
27+
* JSON Schema v6 `const` keyword converted to `enum`
28+
*/
29+
const normalizedSchema = replaceAllConstForEnum(this.schema);
30+
2531
/**
2632
* format: false -> improves generation performances
2733
* ignoreMinAndMaxItems: true -> maxItems: 100 in provider.s3.corsConfiguration definition is generating 100 tuples
2834
*/
29-
const compiledDefinitions = await compile(this.schema, 'AWS', { format: false, ignoreMinAndMaxItems: true })
35+
const compiledDefinitions = await compile(normalizedSchema, 'AWS', { format: false, ignoreMinAndMaxItems: true })
3036
fs.writeFileSync('index.d.ts', compiledDefinitions)
3137
}
3238
}
3339

40+
function replaceAllConstForEnum(schema) {
41+
if ('object' !== typeof schema) {
42+
return schema
43+
}
44+
45+
return Object.fromEntries(Object.entries(schema).map(([key, value]) => {
46+
if (key === 'const') {
47+
return ['enum', [value]]
48+
}
49+
50+
if (Array.isArray(value)) {
51+
return [key, value.map(replaceAllConstForEnum)]
52+
}
53+
54+
if ('object' === typeof value && value !== null) {
55+
return [key, replaceAllConstForEnum(value)]
56+
}
57+
58+
return [key, value]
59+
}))
60+
}
61+
3462
module.exports = ConfigSchemaHandlerTypescriptDefinitionsPlugin

0 commit comments

Comments
 (0)