Skip to content

Commit

Permalink
Support serialization of object examples on unions
Browse files Browse the repository at this point in the history
  • Loading branch information
RichardCPoint committed Nov 23, 2024
1 parent 1226640 commit 4cc2335
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
4 changes: 3 additions & 1 deletion packages/compiler/src/lib/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function serializeValueAsJson(
if (type.kind === "ModelProperty") {
return serializeValueAsJson(program, value, type.type, encodeAs ?? getEncode(program, type));
}
console.log({ valueKind: value.valueKind, value, type });
switch (value.valueKind) {
case "NullValue":
return null;
Expand Down Expand Up @@ -72,11 +73,12 @@ function resolveUnions(program: Program, value: ObjectValue, type: Type): Type |
if (type.kind !== "Union") {
return type;
}
const exactValueType = program.checker.getValueExactType(value);
for (const variant of type.variants.values()) {
if (
ignoreDiagnostics(
program.checker.isTypeAssignableTo(
value.type.projectionBase ?? value.type,
exactValueType ?? value.type.projectionBase ?? value.type,
variant.type.projectionBase ?? variant.type,
value,
),
Expand Down
26 changes: 25 additions & 1 deletion packages/compiler/test/decorators/examples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ describe("@example", () => {
});

describe("union", () => {
it("valid", async () => {
it("valid for union member reference", async () => {
const { program, examples, target } = await getExamplesFor(`
@example(test.a)
@test union test {a: "a", b: "b"}
Expand All @@ -182,6 +182,30 @@ describe("@example", () => {
expect(serializeValueAsJson(program, examples[0].value, target)).toEqual("a");
});

it("valid for object value", async () => {
const { program, examples, target } = await getExamplesFor(`
model A {
type: "a";
a: string;
}
model B {
type: "b";
b: numeric;
}
@example(#{
type: "a",
a: "a string",
})
@test union test {a: A, b: B}
`);
expect(examples).toHaveLength(1);
expect(serializeValueAsJson(program, examples[0].value, target)).toEqual({
type: "a",
a: "a string",
});
});

it("emit diagnostic for unassignable value", async () => {
const diagnostics = await diagnoseCode(`
@example(1)
Expand Down

0 comments on commit 4cc2335

Please sign in to comment.