Skip to content

Commit 306688a

Browse files
committed
Add support for allOf, anyOf, and oneOf
1 parent 8104239 commit 306688a

File tree

3 files changed

+90
-1
lines changed

3 files changed

+90
-1
lines changed

example.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,35 @@ func OpenAPIExample(mode Mode, schema *openapi3.Schema) (interface{}, error) {
100100
return ex, nil
101101
}
102102

103+
// Handle combining keywords
104+
if len(schema.OneOf) > 0 {
105+
return OpenAPIExample(mode, schema.OneOf[0].Value)
106+
}
107+
if len(schema.AnyOf) > 0 {
108+
return OpenAPIExample(mode, schema.AnyOf[0].Value)
109+
}
110+
if len(schema.AllOf) > 0 {
111+
example := map[string]interface{}{}
112+
113+
for _, allOf := range schema.AllOf {
114+
candidate, err := OpenAPIExample(mode, allOf.Value)
115+
if err != nil {
116+
return nil, err
117+
}
118+
119+
value, ok := candidate.(map[string]interface{})
120+
if !ok {
121+
return nil, ErrNoExample
122+
}
123+
124+
for k, v := range value {
125+
example[k] = v
126+
}
127+
}
128+
129+
return example, nil
130+
}
131+
103132
switch {
104133
case schema.Type == "boolean":
105134
return true, nil

example_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,67 @@ var schemaTests = []struct {
417417
}`,
418418
`{"normal": "string", "readOnly": "string"}`,
419419
},
420+
// ----- Combination keywords -----
421+
{
422+
"Combine with allOf",
423+
`{
424+
"allOf": [
425+
{
426+
"type": "object",
427+
"properties": {
428+
"foo": {"type": "string"}
429+
}
430+
},
431+
{
432+
"type": "object",
433+
"properties": {
434+
"bar": {"type": "boolean"}
435+
}
436+
}
437+
]
438+
}`,
439+
`{"foo": "string", "bar": true}`,
440+
},
441+
{
442+
"Combine with anyOf",
443+
`{
444+
"anyOf": [
445+
{
446+
"type": "object",
447+
"properties": {
448+
"foo": {"type": "string"}
449+
}
450+
},
451+
{
452+
"type": "object",
453+
"properties": {
454+
"bar": {"type": "boolean"}
455+
}
456+
}
457+
]
458+
}`,
459+
`{"foo": "string"}`,
460+
},
461+
{
462+
"Combine with oneOf",
463+
`{
464+
"oneOf": [
465+
{
466+
"type": "object",
467+
"properties": {
468+
"foo": {"type": "string"}
469+
}
470+
},
471+
{
472+
"type": "object",
473+
"properties": {
474+
"bar": {"type": "boolean"}
475+
}
476+
}
477+
]
478+
}`,
479+
`{"foo": "string"}`,
480+
},
420481
}
421482

422483
func TestGenExample(t *testing.T) {

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ module github.com/danielgtaylor/apisprout
33
go 1.12
44

55
require (
6-
github.com/davecgh/go-spew v1.1.1
76
github.com/fsnotify/fsnotify v1.4.7
87
github.com/getkin/kin-openapi v0.2.0
98
github.com/gobwas/glob v0.2.3

0 commit comments

Comments
 (0)