-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.go
96 lines (85 loc) · 2.23 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package shiftapi
import (
"fmt"
"net/http"
"reflect"
"github.com/fcjr/shiftapi/internal/utils"
"github.com/getkin/kin-openapi/openapi3"
)
func (s *ShiftAPI) updateSchema(method, path string, handlerFunc, in, out reflect.Type, status int, opts *HandlerOpts) error {
inSchema, err := s.generateSchemaRef(in)
if err != nil {
return err
}
outSchema, err := s.generateSchemaRef(out)
if err != nil {
return err
}
responses := make(openapi3.Responses)
responseContent := make(map[string]*openapi3.MediaType)
responseContent["application/json"] = &openapi3.MediaType{
Schema: &openapi3.SchemaRef{
Ref: fmt.Sprintf("#/components/schemas/%s", outSchema.Ref),
},
}
responses[fmt.Sprint(status)] = &openapi3.ResponseRef{
Value: &openapi3.Response{
Description: utils.String("Success"),
Content: responseContent,
},
}
requestContent := make(map[string]*openapi3.MediaType)
requestContent["application/json"] = &openapi3.MediaType{
Schema: &openapi3.SchemaRef{
Ref: fmt.Sprintf("#/components/schemas/%s", inSchema.Ref),
},
}
requestBody := &openapi3.RequestBodyRef{
Value: &openapi3.RequestBody{
Content: requestContent,
},
}
var oPath *openapi3.PathItem
switch method {
case http.MethodPost:
oPath = &openapi3.PathItem{
Post: &openapi3.Operation{
Summary: opts.Summary,
RequestBody: requestBody,
Description: opts.Description,
Responses: responses,
},
}
}
if oPath == nil {
return fmt.Errorf("method '%s' not implemented", method)
}
s.schema.Paths[path] = oPath
s.schema.Components.Responses.Default()
s.schema.Components.Schemas[inSchema.Ref] = &openapi3.SchemaRef{
Value: inSchema.Value,
}
s.schema.Components.Schemas[outSchema.Ref] = &openapi3.SchemaRef{
Value: outSchema.Value,
}
return nil
}
func (s *ShiftAPI) generateSchemaRef(t reflect.Type) (*openapi3.SchemaRef, error) {
schema, err := s.schemaGen.GenerateSchemaRef(t)
if err != nil {
return nil, err
}
// TODO why tf does kin set ref values for basic types
scrubRefs(schema)
return schema, nil
}
func scrubRefs(s *openapi3.SchemaRef) {
if s.Value.Properties == nil || len(s.Value.Properties) <= 0 {
return
}
for _, p := range s.Value.Properties {
if p.Value.Type != "object" {
p.Ref = ""
}
}
}