-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.go
More file actions
402 lines (352 loc) Β· 10.2 KB
/
Copy pathparse.go
File metadata and controls
402 lines (352 loc) Β· 10.2 KB
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
package swagger
import (
"reflect"
"slices"
"strings"
"time"
"github.com/tinh-tinh/tinhtinh/v2/common"
"github.com/tinh-tinh/tinhtinh/v2/core"
)
// ParsePaths parse all routes in the app and create a swagger spec.
//
// This method will loop through all routes in the app and parse the route
// path, method, and dtos. It will then create a swagger spec in the
// spec.Paths and spec.Definitions fields.
//
// The rules for parsing the route path are as follows:
// - If the route path contains a path parameter, it will be replaced with
// {parameter_name}.
// - If the route path contains multiple path parameters, they will be
// replaced with {parameter_name1}/{parameter_name2}/.../{parameter_nameN}
//
// The rules for parsing the dtos are as follows:
// - If the dto is in the body, it will be replaced with the name of the
// dto in the definitions section.
// - If the dto is in the query or path, it will be replaced with the name
// of the dto in the parameters section.
func (spec *SpecBuilder) ParsePaths(app *core.App) {
// mapperDoc := app.Module.MapperDoc
routes := app.Module.GetRouters()
pathObject := make(PathObject)
schemas := make(map[string]*SchemaObject)
// Parse routes
for _, route := range routes {
parseRoute := core.ParseRoute(route.Method + " " + route.Path)
parseRoute.SetPrefix(route.Name)
if app.Prefix != "" {
parseRoute.SetPrefix(app.Prefix)
}
parameters := []*ParameterObject{}
mediaTypes := make(map[string]*MediaTypeObject)
dtos := route.Dtos
// Parse dto from pipe
for _, dto := range dtos {
val := dto.GetValue()
switch dto.GetLocation() {
case core.InBody:
schemas[common.GetStructName(val)] = ParseSchema(val)
mediaTypes[common.GetStructName(val)] = &MediaTypeObject{
Schema: &SchemaObject{
Ref: "#/components/schemas/" + common.GetStructName(val),
},
}
case core.InQuery:
parameters = append(parameters, ScanQuery(val, dto.GetLocation())...)
case core.InPath:
parameters = append(parameters, ScanQuery(val, dto.GetLocation())...)
}
}
fileIdx := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool {
return v.Key == FILE
})
if fileIdx != -1 {
files, ok := route.Metadata[fileIdx].Value.([]FileOptions)
if ok {
for _, file := range files {
parameters = append(parameters, &ParameterObject{
Name: file.Name,
In: "formData",
// Type: "file",
Required: file.Required,
Description: file.Description,
Schema: &SchemaObject{
Type: "file",
},
})
}
}
}
if pathObject[parseRoute.Path] == nil {
pathObject[parseRoute.Path] = &PathItemObject{}
}
itemObject := pathObject[parseRoute.Path]
response := &ResponseObject{
Description: "Ok",
}
findOkIdx := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool {
return v.Key == OK_RESPONSE
})
if findOkIdx != -1 {
res := route.Metadata[findOkIdx].Value
schemas[common.GetStructName(res)] = ParseSchema(res)
content := &ContentObject{
Schema: &SchemaObject{
Ref: "#/components/schemas/" + common.GetStructName(res),
},
}
response.Content = map[string]*ContentObject{
"application/json": content,
}
}
res := map[string]*ResponseObject{"200": response}
operation := &OperationObject{
Tags: []string{},
Consumes: []string{},
Parameters: parameters,
Responses: res,
Security: []map[string][]string{},
}
if len(mediaTypes) > 0 {
operation.RequestBody = &RequestBodyObject{
Content: mediaTypes,
Required: true,
}
}
// Api Tag
tagIndex := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool { return v.Key == TAG })
if tagIndex != -1 {
tags, ok := route.Metadata[tagIndex].Value.([]string)
if ok {
operation.Tags = tags
}
}
// Api Description
descriptionIndex := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool { return v.Key == DESCRIPTION })
if descriptionIndex != -1 {
description, ok := route.Metadata[descriptionIndex].Value.(string)
if ok {
operation.Description = description
}
}
// Api Summary
summaryIndex := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool { return v.Key == SUMMARY })
if summaryIndex != -1 {
summary, ok := route.Metadata[summaryIndex].Value.(string)
if ok {
operation.Summary = summary
}
}
// Api Security
secureIndex := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool { return v.Key == SECURITY })
if secureIndex != -1 {
securities, ok := route.Metadata[secureIndex].Value.([]string)
if ok {
security := map[string][]string{}
for _, s := range securities {
security[s] = []string{}
}
operation.Security = append(operation.Security, security)
}
}
// Api Consumer
consumerIndex := slices.IndexFunc(route.Metadata, func(v *core.Metadata) bool { return v.Key == CONSUMER })
if consumerIndex != -1 {
consumers, ok := route.Metadata[consumerIndex].Value.([]string)
if ok {
operation.Consumes = consumers
}
}
// Matching method
switch parseRoute.Method {
case "GET":
itemObject.Get = operation
case "POST":
itemObject.Post = operation
case "PUT":
itemObject.Put = operation
case "PATCH":
itemObject.Patch = operation
case "DELETE":
itemObject.Delete = operation
}
}
// spec.Definitions = definitions
spec.Components.Schemas = schemas
spec.Paths = pathObject
}
type Mapper map[string]any
// ParseSchema recursively parses a struct into a SchemaObject definition.
func ParseSchema(dto any) *SchemaObject {
if dto == nil {
return nil
}
v := reflect.ValueOf(dto)
t := reflect.TypeOf(dto)
// Dereference pointers
if v.Kind() == reflect.Ptr {
v = v.Elem()
t = t.Elem()
}
// Only handle structs
if v.Kind() != reflect.Struct {
return &SchemaObject{Type: mappingType(t)}
}
properties := make(map[string]*SchemaObject)
var requiredFields []string
for i := 0; i < t.NumField(); i++ {
fieldType := t.Field(i)
// Skip unexported fields
if fieldType.PkgPath != "" {
continue
}
// Skip hidden fields
if fieldType.Tag.Get("hidden") != "" {
continue
}
// Determine JSON name
jsonTag := fieldType.Tag.Get("json")
fieldName := parseJSONName(jsonTag, fieldType.Name)
if fieldName == "" {
continue
}
schema := &SchemaObject{
Type: mappingType(fieldType.Type),
}
// Handle time.Time format
if isTimeType(fieldType.Type) {
schema.Format = "date-time"
}
// Parse validation tags
validations := strings.Split(fieldType.Tag.Get("validate"), ",")
if slices.Contains(validations, "required") {
requiredFields = append(requiredFields, fieldName)
}
// Parse example
if example := fieldType.Tag.Get("example"); example != "" {
if schema.Type == "array" {
schema.Example = strings.Split(example, ",")
} else {
schema.Example = example
}
}
// Handle nested fields
if slices.Contains(validations, "nested") {
schema = parseNested(fieldType.Type)
} else if schema.Type == "array" {
elemType := fieldType.Type.Elem()
schema.Items = &ItemsObject{Type: mappingType(elemType)}
}
properties[fieldName] = schema
}
return &SchemaObject{
Type: "object",
Properties: properties,
Required: requiredFields,
}
}
// --- helpers ---
func parseJSONName(tag, fallback string) string {
if tag == "-" {
return ""
}
if tag == "" {
return strings.ToLower(fallback)
}
return strings.Split(tag, ",")[0]
}
func isTimeType(t reflect.Type) bool {
return t == reflect.TypeOf(time.Time{})
}
func parseNested(t reflect.Type) *SchemaObject {
// Handle pointer or slice types
switch t.Kind() {
case reflect.Ptr:
if t.Elem().Kind() == reflect.Struct {
return ParseSchema(reflect.New(t.Elem()).Interface())
}
case reflect.Slice, reflect.Array:
elemType := t.Elem()
switch elemType.Kind() {
case reflect.Struct:
// Array of struct
return &SchemaObject{
Type: "array",
Items: &ItemsObject{
Type: "object",
Properties: ParseSchema(reflect.New(elemType).Interface()).Properties,
},
}
case reflect.Ptr:
// Array of pointer to struct
if elemType.Elem().Kind() == reflect.Struct {
return &SchemaObject{
Type: "array",
Items: &ItemsObject{
Type: "object",
Properties: ParseSchema(reflect.New(elemType.Elem()).Interface()).Properties,
},
}
}
fallthrough
default:
// Array of primitive type (string, int, etc.)
return &SchemaObject{
Type: "array",
Items: &ItemsObject{
Type: mappingType(elemType),
},
}
}
case reflect.Struct:
return ParseSchema(reflect.New(t).Interface())
}
return &SchemaObject{Type: mappingType(t)}
}
// ScanQuery takes a struct and recursively parses its fields to create a swagger-style mapper.
// The mapper is a slice of ParameterObject where the keys are the field names (lowercased) and the values are the
// field values. The rules for parsing the fields are as follows:
//
// - If the field is a pointer, it is recursively parsed.
// - If the field is a map, its values are recursively parsed.
// - If the field is a slice, its elements are recursively parsed.
// - If the field is a primitive type, its value is used as is.
//
// The function returns a slice of ParameterObject or nil if the input is nil.
func ScanQuery(val any, in core.CtxKey) []*ParameterObject {
ct := reflect.ValueOf(val).Elem()
params := []*ParameterObject{}
for i := 0; i < ct.NumField(); i++ {
field := ct.Type().Field(i)
// Skip hidden fields
if field.Tag.Get("hidden") != "" {
continue
}
name := ""
if in == core.InQuery {
name = field.Tag.Get("query")
} else {
name = field.Tag.Get("path")
}
param := &ParameterObject{
Name: name,
// Type: mappingType(ct.Field(i)),
Schema: &SchemaObject{
Type: mappingType(ct.Field(i).Type()),
},
In: string(in),
}
validator := field.Tag.Get("validate")
isRequired := slices.IndexFunc(strings.Split(validator, ","), func(v string) bool { return v == "required" })
if isRequired == -1 {
param.Required = false
} else {
param.Required = true
}
example := field.Tag.Get("example")
if example != "" {
param.Default = example
}
params = append(params, param)
}
return params
}