Skip to content

Commit 0299c68

Browse files
heiskrCopilot
andauthored
Fix duplicate codeExamples keys for multi-status-code REST responses (#60530)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 5cb0ae6 commit 0299c68

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/rest/scripts/utils/create-rest-examples.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -328,11 +328,11 @@ export function getResponseExamples(operation: Operation): ResponseExample[] {
328328
// This is a fallback to allow using the `example` property in
329329
// the schema. If we start to enforce using examples vs. example using
330330
// a linter, we can remove the check for `example`.
331-
// For now, we'll use the key default, which is a common default
332-
// example name in the OpenAPI schema.
331+
// We key by statusCode so that operations with multiple success
332+
// responses (e.g. 200 + 201) get unique keys instead of colliding.
333333
if (operation.responses[statusCode].content[contentType].example) {
334334
examples = {
335-
default: {
335+
[statusCode]: {
336336
value: operation.responses[statusCode].content[contentType].example,
337337
},
338338
}

src/rest/tests/create-rest-examples.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { describe, expect, test } from 'vitest'
22

3-
import getCodeSamples, { mergeExamples } from '../scripts/utils/create-rest-examples'
3+
import getCodeSamples, {
4+
mergeExamples,
5+
getResponseExamples,
6+
} from '../scripts/utils/create-rest-examples'
47
import {
58
operation,
69
noContent,
@@ -63,4 +66,31 @@ describe('rest example requests and responses', () => {
6366
)
6467
}
6568
})
69+
70+
test('response examples have unique keys when multiple status codes use inline example', () => {
71+
const multiStatusOp = {
72+
responses: {
73+
200: {
74+
description: 'Response when already exists',
75+
content: {
76+
'application/json': {
77+
example: { id: 1, status: 'existing' },
78+
},
79+
},
80+
},
81+
201: {
82+
description: 'Response when created',
83+
content: {
84+
'application/json': {
85+
example: { id: 1, status: 'created' },
86+
},
87+
},
88+
},
89+
},
90+
}
91+
const examples = getResponseExamples(multiStatusOp)
92+
const keys = examples.map((e) => e.key)
93+
expect(keys).toEqual(['200', '201'])
94+
expect(new Set(keys).size).toBe(keys.length)
95+
})
6696
})

0 commit comments

Comments
 (0)