Skip to content

Commit 5537c80

Browse files
authored
Escape constant string in generated schema (#1014)
* Escape strings in constants * Adjust and extend test for constant string value * Run prettier
1 parent 3ffb475 commit 5537c80

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/transform/schema-object.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,13 @@ export function defaultSchemaObjectTransform(
6262

6363
// const (valid for any type)
6464
if (schemaObject.const) {
65-
return transformSchemaObject(schemaObject.const as any, {
65+
let schemaConst = schemaObject.const as any;
66+
if ("type" in schemaObject) {
67+
if (schemaObject.type === "string") {
68+
schemaConst = escStr(schemaConst)
69+
}
70+
}
71+
return transformSchemaObject(schemaConst, {
6672
path,
6773
ctx: { ...ctx, immutableTypes: false, indentLv: indentLv + 1 }, // note: guarantee readonly happens once, here
6874
});

test/schema-object.test.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,19 @@ describe("Schema Object", () => {
134134
}`);
135135
});
136136

137+
test("const string field", () => {
138+
const schema: SchemaObject = {
139+
type: "object",
140+
properties: { constant: { const: "a", type: "string" } },
141+
required: ["constant"],
142+
};
143+
const generated = transformSchemaObject(schema, options);
144+
expect(generated).toBe(`{
145+
/** @constant */
146+
constant: "a";
147+
}`);
148+
});
149+
137150
test("additionalProperties with properties", () => {
138151
const schema: SchemaObject = {
139152
type: "object",
@@ -186,7 +199,7 @@ describe("Schema Object", () => {
186199
describe("const", () => {
187200
test("string", () => {
188201
const generated = transformSchemaObject({ type: "string", const: "duck" }, options);
189-
expect(generated).toBe("duck");
202+
expect(generated).toBe(`"duck"`);
190203
});
191204
});
192205

0 commit comments

Comments
 (0)