判别器上下文

以 Markdown 格式查看

x-fern-discriminator-context 扩展告诉 Fern 判别联合体的判别器字段位于何处:数据有效载荷内部(data,默认值)还是协议帧级别(protocol)。此区别对于 SSE 端点很重要,其中 event 字段是 SSE 协议的一部分,而不是 data 有效载荷内的属性。

含义
data判别器是 JSON 主体内的属性(默认)
protocol判别器位于协议级别(例如 SSE event 字段)

x-fern-discriminator-context 放置在 oneOf schema 的 discriminator 对象上。

协议级判别(SSE)

在 SSE 协议中,event 字段是线路帧的一部分,不包含在解析后的 data 有效载荷中。设置 x-fern-discriminator-context: protocol 告诉 Fern 和生成的 SDK 判别符位于数据之外,因此它们在反序列化每个变体的 data 时不会期望判别符属性存在。

openapi.yml
1components:
2 schemas:
3 StreamEvent:
4 discriminator:
5 propertyName: event
6 x-fern-discriminator-context: protocol
7 mapping:
8 completion: "#/components/schemas/CompletionEvent"
9 error: "#/components/schemas/ErrorEvent"
10 oneOf:
11 - $ref: "#/components/schemas/CompletionEvent"
12 - $ref: "#/components/schemas/ErrorEvent"
13
14 CompletionEvent:
15 type: object
16 properties:
17 content:
18 type: string
19
20 ErrorEvent:
21 type: object
22 properties:
23 message:
24 type: string
25 code:
26 type: integer

对应的 SSE 流如下:

event: completion
data: {"content": "Hello"}
event: error
data: {"message": "Rate limited", "code": 429}

如果没有 x-fern-discriminator-context: protocol,Fern 会将 event 视为每个变体 JSON 主体内的字段,并期望它出现在 data 有效载荷中。

数据级判别(默认)

当省略 x-fern-discriminator-context 或将其设置为 data 时,判别器是 JSON 主体内的属性。这是标准的 OpenAPI 判别联合体行为,不需要扩展。

openapi.yml
1components:
2 schemas:
3 Plant:
4 discriminator:
5 propertyName: type
6 mapping:
7 tree: "#/components/schemas/Tree"
8 flower: "#/components/schemas/Flower"
9 oneOf:
10 - $ref: "#/components/schemas/Tree"
11 - $ref: "#/components/schemas/Flower"
12
13 Tree:
14 type: object
15 required:
16 - type
17 properties:
18 type:
19 type: string
20 enum: ["tree"]
21 height:
22 type: number
23
24 Flower:
25 type: object
26 required:
27 - type
28 properties:
29 type:
30 type: string
31 enum: ["flower"]
32 color:
33 type: string

自动推断

当判别联合体中的每个变体仅使用 SSE 规范字段(eventdataidretry)及其预期类型时,Fern 会自动推断 protocol 上下文。在这种情况下,无需添加扩展。当您想要覆盖推断值或变体 schema 与 SSE 形状不完全匹配时,请显式使用 x-fern-discriminator-context