| 235 | } |
| 236 | */ |
| 237 | export function getResponseExamples(operation) { |
| 238 | const responseExamples = [] |
| 239 | Object.keys(operation.responses).forEach((statusCode) => { |
| 240 | // We don't want to create examples for error codes |
| 241 | // Error codes are displayed in the status table in the docs |
| 242 | if (parseInt(statusCode, 10) >= 400) return |
| 243 | |
| 244 | const content = operation.responses[statusCode].content |
| 245 | |
| 246 | // A response doesn't always have content (ex:, status 304) |
| 247 | // In this case we create a generic example for the status code |
| 248 | // with a key that matches the status code. |
| 249 | if (!content) { |
| 250 | const example = { |
| 251 | key: statusCode, |
| 252 | response: { |
| 253 | statusCode, |
| 254 | description: operation.responses[statusCode].description, |
| 255 | }, |
| 256 | } |
| 257 | responseExamples.push(example) |
| 258 | return |
| 259 | } |
| 260 | |
| 261 | // Responses can have multiple content types each with their own set of |
| 262 | // examples. |
| 263 | Object.keys(content).forEach((contentType) => { |
| 264 | let examples = {} |
| 265 | // This is a fallback to allow using the `example` property in |
| 266 | // the schema. If we start to enforce using examples vs. example using |
| 267 | // a linter, we can remove the check for `example`. |
| 268 | // For now, we'll use the key default, which is a common default |
| 269 | // example name in the OpenAPI schema. |
| 270 | if (operation.responses[statusCode].content[contentType].example) { |
| 271 | examples = { |
| 272 | default: { |
| 273 | value: operation.responses[statusCode].content[contentType].example, |
| 274 | }, |
| 275 | } |
| 276 | } else if (operation.responses[statusCode].content[contentType].examples) { |
| 277 | examples = operation.responses[statusCode].content[contentType].examples |
| 278 | } else if (parseInt(statusCode, 10) < 300) { |
| 279 | // Sometimes there are missing examples for say a 200 response and |
| 280 | // the operation also has a 304 no content status. If we don't add |
| 281 | // the 200 response example, even though it has not example response, |
| 282 | // the resulting responseExamples would only contain the 304 response. |
| 283 | // That would be confusing in the docs because it's expected to see the |
| 284 | // common or success responses by default. |
| 285 | const example = { |
| 286 | key: statusCode, |
| 287 | response: { |
| 288 | statusCode, |
| 289 | description: operation.responses[statusCode].description, |
| 290 | }, |
| 291 | } |
| 292 | responseExamples.push(example) |
| 293 | return |
| 294 | } else { |