forked from go-generation/go-mvc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.go
More file actions
89 lines (77 loc) · 2.47 KB
/
generator.go
File metadata and controls
89 lines (77 loc) · 2.47 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
package gomvc
import (
"log"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/iancoleman/strcase"
"github.com/jinzhu/inflection"
)
// Generator wraps functionality for reading and manipulating a single OpenAPI spec
type Generator struct {
oa3 *openapi3.Swagger
}
// NewGenerator is a constructor for Generator
func NewGenerator(oa3 *openapi3.Swagger) Generator {
return Generator{
oa3: oa3,
}
}
// CreateControllerFiles creates a controller for operations found in
// an OpenAPI file
func (oag *Generator) CreateControllerFiles(path string, pathItem *openapi3.PathItem, dest string, templateDir string) error {
name := strcase.ToSnake(pathItem.Summary)
name = strings.ToLower(name)
if name == "" {
log.Printf("No summary provided in API, defaulting to deriving name from path %s since we can't identify a name for the resource", path)
name = getControllerNameFromPath(path)
}
log.Printf("Preparing to generate controller files for %s %s", name, path)
data := ControllerData{
Name: name,
PluralName: inflection.Plural(name),
Path: path,
Actions: []Action{},
}
var responses []Response
responseSet := map[string]bool{}
// collect controller methods based on specified HTTP verbs/operations
for method, op := range pathItem.Operations() {
var handler = getDefaultHandlerName(method, path)
var operationName string
if op.OperationID == "" {
log.Printf("Missing operation ID. Generating default name for handler/operation function in controller %s.\n", name)
operationName = handler
} else {
operationName = strings.Title(op.OperationID)
}
// responses might not be unique across controller actions
// so this ensures that any associated generation happens once
// additionally, we only care about the error responses
// to generate filter functions
opResponses := NewResponses(op.Responses)
for _, r := range opResponses {
if r.Code < 400 {
continue
}
if _, ok := responseSet[r.Name]; !ok {
responseSet[r.Name] = true
responses = append(responses, r)
}
}
a := Action{
SingularResource: inflection.Singular(name),
Resource: name,
Method: method,
Path: path,
Handler: handler,
Name: operationName,
}
data.Actions = append(data.Actions, a)
}
data.ErrorResponses = responses
if err := createControllerFromDefault(data, dest); err != nil {
return err
}
log.Printf("created controller actions for %s\n", path)
return nil
}