Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: fix
packages:
- "@typespec/openapi3"
---

Fix parameters with default value resulting in `$ref` with `default` as sibling for OpenAPI 3.0
10 changes: 8 additions & 2 deletions packages/openapi3/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1577,15 +1577,21 @@ function createOAPIEmitter(
if (!typeSchema) {
return undefined;
}
const schema = applyEncoding(
let schema = applyEncoding(
program,
param,
applyIntrinsicDecorators(param, typeSchema),
options,
);

if (param.defaultValue) {
schema.default = getDefaultValue(program, param.defaultValue, param);
const defaultValue = getDefaultValue(program, param.defaultValue, param);
// In OpenAPI 3.0, $ref cannot have sibling properties.
if ("$ref" in schema && specVersion === "3.0.0") {
schema = { allOf: [{ $ref: schema.$ref }], default: defaultValue };
} else {
schema.default = defaultValue;
}
}
// Description is already provided in the parameter itself.
delete schema.description;
Expand Down
22 changes: 21 additions & 1 deletion packages/openapi3/test/parameters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { describe, expect, it } from "vitest";
import { OpenAPI3PathParameter, OpenAPI3QueryParameter } from "../src/types.js";
import { supportedVersions, worksFor } from "./works-for.js";

worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor, version }) => {
describe("query parameters", () => {
async function getQueryParam(code: string): Promise<OpenAPI3QueryParameter> {
const res = await openApiFor(code);
Expand Down Expand Up @@ -616,4 +616,24 @@ worksFor(supportedVersions, ({ diagnoseOpenApiFor, openApiFor }) => {
});
});
});

it("parmeter with default value and $ref wraps $ref in allOf in OpenAPI 3.0 only", async () => {
const res = await openApiFor(
`
enum Example { a, b}
op test(@query example?: Example = Example.b): void;
`,
);

const schema = res.paths["/"].get.parameters[0].schema;
if (version === "3.0.0") {
// In OpenAPI 3.0, $ref cannot have sibling properties, so we wrap in allOf
expect(schema.allOf).toEqual([{ $ref: "#/components/schemas/Example" }]);
expect(schema.default).toBe("b");
} else {
// In OpenAPI 3.1+, $ref can have sibling properties
expect(schema.$ref).toBe("#/components/schemas/Example");
expect(schema.default).toBe("b");
}
});
});
Loading