forked from danielgtaylor/apisprout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.go
300 lines (251 loc) · 6.91 KB
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main
import (
"fmt"
"github.com/getkin/kin-openapi/openapi3"
)
// Mode defines a mode of operation for example generation.
type Mode int
const (
// ModeRequest is for the request body (writes to the server)
ModeRequest Mode = iota
// ModeResponse is for the response body (reads from the server)
ModeResponse
)
func getSchemaExample(schema *openapi3.Schema) (interface{}, bool) {
if schema.Example != nil {
return schema.Example, true
}
if schema.Default != nil {
return schema.Default, true
}
if schema.Enum != nil && len(schema.Enum) > 0 {
return schema.Enum[0], true
}
return nil, false
}
// stringFormatExample returns an example string based on the given format.
// http://json-schema.org/latest/json-schema-validation.html#rfc.section.7.3
func stringFormatExample(format string) string {
switch format {
case "date":
// https://tools.ietf.org/html/rfc3339
return "2018-07-23"
case "date-time":
// This is the date/time of API Sprout's first commit! :-)
return "2018-07-23T22:58:00-07:00"
case "time":
return "22:58:00-07:00"
case "email":
return "[email protected]"
case "hostname":
// https://tools.ietf.org/html/rfc2606#page-2
return "example.com"
case "ipv4":
// https://tools.ietf.org/html/rfc5737
return "198.51.100.0"
case "ipv6":
// https://tools.ietf.org/html/rfc3849
return "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
case "uri":
return "https://tools.ietf.org/html/rfc3986"
case "uri-template":
// https://tools.ietf.org/html/rfc6570
return "http://example.com/dictionary/{term:1}/{term}"
case "json-pointer":
// https://tools.ietf.org/html/rfc6901
return "#/components/parameters/term"
case "regex":
// https://stackoverflow.com/q/3296050/164268
return "/^1?$|^(11+?)\\1+$/"
case "uuid":
// https://www.ietf.org/rfc/rfc4122.txt
return "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
case "password":
return "********"
}
return ""
}
// excludeFromMode will exclude a schema if the mode is request and the schema
// is read-only, or if the mode is response and the schema is write only.
func excludeFromMode(mode Mode, schema *openapi3.Schema) bool {
if schema == nil {
return true
}
if mode == ModeRequest && schema.ReadOnly {
return true
} else if mode == ModeResponse && schema.WriteOnly {
return true
}
return false
}
// isRequired checks whether a key is actually required.
func isRequired(schema *openapi3.Schema, key string) bool {
for _, req := range schema.Required {
if req == key {
return true
}
}
return false
}
type cachedSchema struct {
pending bool
out interface{}
}
func openAPIExample(mode Mode, schema *openapi3.Schema, cache map[*openapi3.Schema]*cachedSchema) (out interface{}, err error) {
if ex, ok := getSchemaExample(schema); ok {
return ex, nil
}
cached, ok := cache[schema]
if !ok {
cached = &cachedSchema{
pending: true,
}
cache[schema] = cached
} else if cached.pending {
return nil, ErrRecursive
} else {
return cached.out, nil
}
defer func() {
cached.pending = false
cached.out = out
}()
// Handle combining keywords
if len(schema.OneOf) > 0 {
var ex interface{}
var err error
for _, candidate := range schema.OneOf {
ex, err = openAPIExample(mode, candidate.Value, cache)
if err == nil {
break
}
}
return ex, err
}
if len(schema.AnyOf) > 0 {
var ex interface{}
var err error
for _, candidate := range schema.AnyOf {
ex, err = openAPIExample(mode, candidate.Value, cache)
if err == nil {
break
}
}
return ex, err
}
if len(schema.AllOf) > 0 {
example := map[string]interface{}{}
for _, allOf := range schema.AllOf {
candidate, err := openAPIExample(mode, allOf.Value, cache)
if err != nil {
return nil, err
}
value, ok := candidate.(map[string]interface{})
if !ok {
return nil, ErrNoExample
}
for k, v := range value {
example[k] = v
}
}
return example, nil
}
switch {
case schema.Type == "boolean":
return true, nil
case schema.Type == "number", schema.Type == "integer":
value := 0.0
if schema.Min != nil && *schema.Min > value {
value = *schema.Min
if schema.ExclusiveMin {
if schema.Max != nil {
// Make the value half way.
value = (*schema.Min + *schema.Max) / 2.0
} else {
value++
}
}
}
if schema.Max != nil && *schema.Max < value {
value = *schema.Max
if schema.ExclusiveMax {
if schema.Min != nil {
// Make the value half way.
value = (*schema.Min + *schema.Max) / 2.0
} else {
value--
}
}
}
if schema.MultipleOf != nil && int(value)%int(*schema.MultipleOf) != 0 {
value += float64(int(*schema.MultipleOf) - (int(value) % int(*schema.MultipleOf)))
}
if schema.Type == "integer" {
return int(value), nil
}
return value, nil
case schema.Type == "string":
if ex := stringFormatExample(schema.Format); ex != "" {
return ex, nil
}
example := "string"
for schema.MinLength > uint64(len(example)) {
example += example
}
if schema.MaxLength != nil && *schema.MaxLength < uint64(len(example)) {
example = example[:*schema.MaxLength]
}
return example, nil
case schema.Type == "array", schema.Items != nil:
example := []interface{}{}
if schema.Items != nil && schema.Items.Value != nil {
ex, err := openAPIExample(mode, schema.Items.Value, cache)
if err != nil {
return nil, fmt.Errorf("can't get example for array item: %+v", err)
}
example = append(example, ex)
for uint64(len(example)) < schema.MinItems {
example = append(example, ex)
}
}
return example, nil
case schema.Type == "object", len(schema.Properties) > 0:
example := map[string]interface{}{}
for k, v := range schema.Properties {
if excludeFromMode(mode, v.Value) {
continue
}
ex, err := openAPIExample(mode, v.Value, cache)
if err == ErrRecursive {
if isRequired(schema, k) {
return nil, fmt.Errorf("can't get example for '%s': %+v", k, err)
}
} else if err != nil {
return nil, fmt.Errorf("can't get example for '%s': %+v", k, err)
} else {
example[k] = ex
}
}
if schema.AdditionalProperties != nil && schema.AdditionalProperties.Value != nil {
addl := schema.AdditionalProperties.Value
if !excludeFromMode(mode, addl) {
ex, err := openAPIExample(mode, addl, cache)
if err == ErrRecursive {
// We just won't add this if it's recursive.
} else if err != nil {
return nil, fmt.Errorf("can't get example for additional properties: %+v", err)
} else {
example["additionalPropertyName"] = ex
}
}
}
return example, nil
}
return nil, ErrNoExample
}
// OpenAPIExample creates an example structure from an OpenAPI 3 schema
// object, which is an extended subset of JSON Schema.
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject
func OpenAPIExample(mode Mode, schema *openapi3.Schema) (interface{}, error) {
return openAPIExample(mode, schema, make(map[*openapi3.Schema]*cachedSchema))
}