This repository has been archived by the owner on Sep 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
schema.go
77 lines (61 loc) · 2.09 KB
/
schema.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
package openapi
import (
"fmt"
)
// Schema -.
type Schema struct {
Properties Schemas `json:"properties,omitempty" yaml:"properties,omitempty"`
Type string `json:"type,omitempty" yaml:"type,omitempty"`
Format string `json:"format,omitempty" yaml:"format,omitempty"`
Default interface{} `json:"default,omitempty" yaml:"default,omitempty"`
Example interface{} `json:"example,omitempty" yaml:"example,omitempty"`
Required []string `json:"required,omitempty" yaml:"required,omitempty"`
Items *Schema `json:"items,omitempty" yaml:"items,omitempty"`
Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"`
MinItems int `json:"minItems,omitempty" yaml:"minItems,omitempty"`
MaxItems int `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
Faker string `json:"x-faker,omitempty" yaml:"x-faker,omitempty"`
}
// IsRef -.
func (s Schema) IsRef() bool {
return s.Ref != ""
}
// Schemas -.
type Schemas map[string]*Schema
// SchemaContext -.
type SchemaContext interface {
LookupSchemaByReference(ref string) (Schema, error)
}
// ResponseByExample -.
func (s Schema) ResponseByExample(schemaContext SchemaContext) (interface{}, error) {
if s.Ref != "" {
schema, err := schemaContext.LookupSchemaByReference(s.Ref)
if err != nil {
return nil, fmt.Errorf("lookup: %w", err)
}
return schema.ResponseByExample(schemaContext)
}
if s.Example != nil {
return ExampleToResponse(s.Example), nil
}
return s.propertiesExamples(schemaContext)
}
func (s Schema) propertiesExamples(schemaContext SchemaContext) (interface{}, error) {
if s.Items != nil {
resp, err := s.Items.ResponseByExample(schemaContext)
if err != nil {
return nil, fmt.Errorf("response from items: %w", err)
}
res := []interface{}{resp}
return res, nil
}
res := make(map[string]interface{}, len(s.Properties))
for key, prop := range s.Properties {
propResp, err := prop.ResponseByExample(schemaContext)
if err != nil {
return nil, fmt.Errorf("response for property %q: %w", key, err)
}
res[key] = propResp
}
return res, nil
}