Skip to content

Commit e2f42d9

Browse files
Copilotmarkcowl
andcommitted
fix(compiler): only return undefined for no-arg scalar constructor, preserve args[0] behavior
Co-authored-by: markcowl <1054056+markcowl@users.noreply.github.com>
1 parent c71203f commit e2f42d9

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

packages/compiler/src/lib/examples.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,11 @@ function serializeScalarValueAsJson(
229229

230230
const result = resolveKnownScalar(program, value.scalar);
231231
if (result === undefined) {
232-
return undefined;
232+
const firstArg = value.value.args[0];
233+
if (firstArg === undefined) {
234+
return undefined;
235+
}
236+
return serializeValueAsJson(program, firstArg, firstArg.type);
233237
}
234238

235239
encodeAs = encodeAs ?? result.encodeAs;

packages/compiler/test/decorators/examples.test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,15 @@ describe("@example", () => {
142142
expect(serializeValueAsJson(program, examples[0].value, target)).toBeUndefined();
143143
});
144144

145-
it("returns undefined for custom scalar with initializer", async () => {
145+
it("serializes first argument for custom scalar with initializer", async () => {
146146
const { program, examples, target } = await getExamplesFor(`
147-
@example(test.i("foo"))
147+
@example(test.name("Shorty"))
148148
@test scalar test {
149-
init i(s: string);
149+
init name(value: string);
150150
}
151151
`);
152152
expect(examples).toHaveLength(1);
153-
expect(serializeValueAsJson(program, examples[0].value, target)).toBeUndefined();
153+
expect(serializeValueAsJson(program, examples[0].value, target)).toEqual("Shorty");
154154
});
155155
});
156156

packages/openapi3/test/models.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,19 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, oapiForModel, openApiFor }) =
275275
expect(res.schemas.Pet.properties.name.default).toEqual("Shorty");
276276
});
277277

278+
it("scalar with no-argument initializer used as a default value does not crash", async () => {
279+
const res = await oapiForModel(
280+
"M",
281+
`
282+
scalar S { init i(); }
283+
284+
model M { p: S = S.i(); }
285+
`,
286+
);
287+
288+
expect(res.schemas.M.properties.p.default).toBeUndefined();
289+
});
290+
278291
it("encode know scalar as a default value", async () => {
279292
const res = await oapiForModel(
280293
"Test",

0 commit comments

Comments
 (0)