在 OpenAPI (Swagger) 中重用枚举的子集 [英] Reusing a subset of an enum in OpenAPI (Swagger)
问题描述
我正在尝试实现一个 OpenAPI 定义,其中我将一个共享的、完整的允许值列表定义为一个枚举,然后在不同位置使用值的子组来显示每种情况下允许哪些值.
I'm trying to achieve an OpenAPI definition where I define a shared, complete list of allowed values as an enum and then use subgroups of the values in different places to show which values are allowed in each case.
使用 Swagger.io 上的枚举规范 中的示例,如果我有这样的定义:
Using the example from the enum spec on Swagger.io, if I have a definition like this:
paths:
/products:
get:
parameters:
- in: query
name: color
required: true
schema:
$ref: '#/components/schemas/Color'
responses:
'200':
description: OK
components:
schemas:
Color:
type: string
enum:
- black
- white
- red
- green
- blue
那么是否可以定义例如两种不同的路径以颜色作为参数,但其中一个只接受 black
或 white
而另一个接受所有颜色?
then is it possible to define e.g. two different paths that take a color as a parameter, but one of them only accepts black
or white
whereas the other accepts all colors?
推荐答案
重用枚举的一部分没有好的方法.最好的方法是定义单独的枚举.
There's no good way to reuse a part of an enum. The best way is to define separate enums.
一种可能的解决方法是使用 oneOf
将部分枚举组合"到完整枚举中,如 此处建议.但是,oneOf
枚举模式可能无法在 Swagger UI 和代码生成器中用作枚举.
A possible workaround is to use oneOf
to "combine" partial enums into the full enum as suggested here. However, oneOf
enum schemas probably won't work as enums in Swagger UI and code generators.
components:
schemas:
BlackOrWhite:
type: string
enum:
- black
- white
Color:
oneOf:
- $ref: '#/components/schemas/BlackOrWhite'
- type: string
enum:
- red
- green
- blue
使用 YAML &anchors
和 merge 键 < 的技巧;<
将不起作用,因为 YAML 仅支持映射(对象)中的合并键但不在序列中(数组).
Tricks with YAML &anchors
and merge keys <<
will NOT work because YAML only supports merge keys in mappings (objects) but not in sequences (arrays).
# This will NOT work in YAML
components:
schemas:
BlackOrWhite:
type: string
enum: &BLACK_WHITE
- black
- white
Color:
type: string
enum:
<< : *BLACK_WHITE
- red
- green
- blue
这篇关于在 OpenAPI (Swagger) 中重用枚举的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!