-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
353 lines (316 loc) · 9.9 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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package rest
import (
"fmt"
"reflect"
"sort"
"strings"
"github.com/a-h/rest/getcomments/parser"
"github.com/getkin/kin-openapi/openapi3"
"golang.org/x/exp/constraints"
)
func newSpec(name string) *openapi3.T {
return &openapi3.T{
OpenAPI: "3.0.0",
Info: &openapi3.Info{
Title: name,
Version: "0.0.0",
Extensions: map[string]interface{}{},
},
Components: &openapi3.Components{
Schemas: make(openapi3.Schemas),
Extensions: map[string]interface{}{},
},
Paths: openapi3.Paths{},
Extensions: map[string]interface{}{},
}
}
func getSortedKeys[V any](m map[string]V) (op []string) {
for k := range m {
op = append(op, k)
}
sort.Slice(op, func(i, j int) bool {
return op[i] < op[j]
})
return op
}
func (api *API) createOpenAPI() (spec *openapi3.T, err error) {
spec = newSpec(api.Name)
// Add all the routes.
for pattern, methodToRoute := range api.Routes {
path := &openapi3.PathItem{}
for method, route := range methodToRoute {
op := &openapi3.Operation{}
// Add the route params.
for _, k := range getSortedKeys(route.Params.Path) {
v := route.Params.Path[k]
ps := openapi3.NewStringSchema()
if v.Regexp != "" {
ps.WithPattern(v.Regexp)
}
param := openapi3.NewPathParameter(k).
WithDescription(v.Description).
WithSchema(ps)
op.AddParameter(param)
}
// Handle request types.
if route.Models.Request.Type != nil {
name, schema, err := api.RegisterModel(route.Models.Request)
if err != nil {
return spec, err
}
op.RequestBody = &openapi3.RequestBodyRef{
Value: openapi3.NewRequestBody().WithContent(map[string]*openapi3.MediaType{
"application/json": {
Schema: getSchemaReferenceOrValue(name, schema),
},
}),
}
}
// Handle response types.
for status, model := range route.Models.Responses {
name, schema, err := api.RegisterModel(model)
if err != nil {
return spec, err
}
resp := openapi3.NewResponse().
WithDescription("").
WithContent(map[string]*openapi3.MediaType{
"application/json": {
Schema: getSchemaReferenceOrValue(name, schema),
},
})
op.AddResponse(status, resp)
}
// Handle tags.
op.Tags = append(op.Tags, route.Tags...)
// Handle OperationID.
op.OperationID = route.OperationID
// Handle description.
op.Description = route.Description
// Register the method.
path.SetOperation(string(method), op)
}
// Populate the OpenAPI schemas from the models.
for name, schema := range api.models {
spec.Components.Schemas[name] = openapi3.NewSchemaRef("", schema)
}
spec.Paths[string(pattern)] = path
}
loader := openapi3.NewLoader()
if err = loader.ResolveRefsIn(spec, nil); err != nil {
return spec, fmt.Errorf("failed to resolve, due to external references: %w", err)
}
if err = spec.Validate(loader.Context); err != nil {
return spec, fmt.Errorf("failed validation: %w", err)
}
return spec, err
}
func (api *API) getModelName(t reflect.Type) string {
pkgPath, typeName := t.PkgPath(), t.Name()
if t.Kind() == reflect.Pointer {
pkgPath = t.Elem().PkgPath()
typeName = t.Elem().Name() + "Ptr"
}
if t.Kind() == reflect.Map {
typeName = fmt.Sprintf("map[%s]%s", t.Key().Name(), t.Elem().Name())
}
schemaName := api.normalizeTypeName(pkgPath, typeName)
if typeName == "" {
schemaName = fmt.Sprintf("AnonymousType%d", len(api.models))
}
return schemaName
}
func getSchemaReferenceOrValue(name string, schema *openapi3.Schema) *openapi3.SchemaRef {
if shouldBeReferenced(schema) {
return openapi3.NewSchemaRef(fmt.Sprintf("#/components/schemas/%s", name), nil)
}
return openapi3.NewSchemaRef("", schema)
}
// ModelOpts defines options that can be set when registering a model.
type ModelOpts func(s *openapi3.Schema)
// WithNullable sets the nullable field to true.
func WithNullable() ModelOpts {
return func(s *openapi3.Schema) {
s.Nullable = true
}
}
// WithDescription sets the description field on the schema.
func WithDescription(desc string) ModelOpts {
return func(s *openapi3.Schema) {
s.Description = desc
}
}
// WithEnumValues sets the property to be an enum value with the specific values.
func WithEnumValues[T ~string | constraints.Integer](values ...T) ModelOpts {
return func(s *openapi3.Schema) {
if len(values) == 0 {
return
}
s.Type = openapi3.TypeString
if reflect.TypeOf(values[0]).Kind() != reflect.String {
s.Type = openapi3.TypeInteger
}
for _, v := range values {
s.Enum = append(s.Enum, v)
}
}
}
// RegisterModel allows a model to be registered manually so that additional configuration can be applied.
// The schema returned can be modified as required.
func (api *API) RegisterModel(model Model, opts ...ModelOpts) (name string, schema *openapi3.Schema, err error) {
// Get the name.
t := model.Type
name = api.getModelName(t)
// If we've already got the schema, return it.
var ok bool
if schema, ok = api.models[name]; ok {
return name, schema, nil
}
// It's known, but not in the schemaset yet.
if schema, ok = api.KnownTypes[t]; ok {
// Objects, enums, need to be references, so add it into the
// list.
if shouldBeReferenced(schema) {
api.models[name] = schema
}
return name, schema, nil
}
var elementName string
var elementSchema *openapi3.Schema
switch t.Kind() {
case reflect.Slice, reflect.Array:
elementName, elementSchema, err = api.RegisterModel(modelFromType(t.Elem()))
if err != nil {
return name, schema, fmt.Errorf("error getting schema of slice element %v: %w", t.Elem(), err)
}
schema = openapi3.NewArraySchema().WithNullable() // Arrays are always nilable in Go.
schema.Items = getSchemaReferenceOrValue(elementName, elementSchema)
case reflect.String:
schema = openapi3.NewStringSchema()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
schema = openapi3.NewIntegerSchema()
case reflect.Float64, reflect.Float32:
schema = openapi3.NewFloat64Schema()
case reflect.Bool:
schema = openapi3.NewBoolSchema()
case reflect.Pointer:
name, schema, err = api.RegisterModel(modelFromType(t.Elem()), WithNullable())
case reflect.Map:
// Check that the key is a string.
if t.Key().Kind() != reflect.String {
return name, schema, fmt.Errorf("maps must have a string key, but this map is of type %q", t.Key().String())
}
// Get the element schema.
elementName, elementSchema, err = api.RegisterModel(modelFromType(t.Elem()))
if err != nil {
return name, schema, fmt.Errorf("error getting schema of map value element %v: %w", t.Elem(), err)
}
schema = openapi3.NewObjectSchema().WithNullable()
schema.AdditionalProperties.Schema = getSchemaReferenceOrValue(elementName, elementSchema)
case reflect.Struct:
schema = openapi3.NewObjectSchema()
if schema.Description, err = api.getTypeComment(t.PkgPath(), t.Name()); err != nil {
return name, schema, fmt.Errorf("failed to get comments for type %q: %w", name, err)
}
schema.Properties = make(openapi3.Schemas)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
// Get JSON fieldName.
fieldName := strings.Split(f.Tag.Get("json"), ",")[0]
if fieldName == "" {
fieldName = f.Name
}
// If the model doesn't exist.
_, alreadyExists := api.models[api.getModelName(f.Type)]
fieldSchemaName, fieldSchema, err := api.RegisterModel(modelFromType(f.Type))
if err != nil {
return name, schema, fmt.Errorf("error getting schema for type %q, field %q, failed to get schema for embedded type %q: %w", t, fieldName, f.Type, err)
}
if f.Anonymous {
// It's an anonymous type, no need for a reference to it,
// since we're copying the fields.
if !alreadyExists {
delete(api.models, fieldSchemaName)
}
// Add all embedded fields to this type.
for name, ref := range fieldSchema.Properties {
schema.Properties[name] = ref
}
continue
}
ref := getSchemaReferenceOrValue(fieldSchemaName, fieldSchema)
if ref.Value != nil {
if ref.Value.Description, err = api.getTypeFieldComment(t.PkgPath(), t.Name(), f.Name); err != nil {
return name, schema, fmt.Errorf("failed to get comments for field %q in type %q: %w", fieldName, name, err)
}
}
schema.Properties[fieldName] = ref
}
}
if schema == nil {
return name, schema, fmt.Errorf("unsupported type: %v/%v", t.PkgPath(), t.Name())
}
for _, opt := range opts {
opt(schema)
}
// After all processing, register the type if required.
if shouldBeReferenced(schema) {
api.models[name] = schema
return
}
return
}
func (api *API) getCommentsForPackage(pkg string) (pkgComments map[string]string, err error) {
if pkgComments, loaded := api.comments[pkg]; loaded {
return pkgComments, nil
}
pkgComments, err = parser.Get(pkg)
if err != nil {
return
}
api.comments[pkg] = pkgComments
return
}
func (api *API) getTypeComment(pkg string, name string) (comment string, err error) {
pkgComments, err := api.getCommentsForPackage(pkg)
if err != nil {
return
}
return pkgComments[pkg+"."+name], nil
}
func (api *API) getTypeFieldComment(pkg string, name string, field string) (comment string, err error) {
pkgComments, err := api.getCommentsForPackage(pkg)
if err != nil {
return
}
return pkgComments[pkg+"."+name+"."+field], nil
}
func shouldBeReferenced(schema *openapi3.Schema) bool {
if schema.Type == openapi3.TypeObject && schema.AdditionalProperties.Schema == nil {
return true
}
if len(schema.Enum) > 0 {
return true
}
return false
}
var normalizer = strings.NewReplacer("/", "_",
".", "_",
"[", "_",
"]", "_")
func (api *API) normalizeTypeName(pkgPath, name string) string {
var omitPackage bool
for _, pkg := range api.StripPkgPaths {
if strings.HasPrefix(pkgPath, pkg) {
omitPackage = true
break
}
}
if omitPackage || pkgPath == "" {
return normalizer.Replace(name)
}
return normalizer.Replace(pkgPath + "/" + name)
}