-
Notifications
You must be signed in to change notification settings - Fork 0
/
templater.go
211 lines (177 loc) · 6.36 KB
/
templater.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
package templater
import (
"bytes"
"errors"
"fmt"
"strings"
"text/template"
"github.com/CubicrootXYZ/openapi-code-sample-generator/internal/log"
"github.com/CubicrootXYZ/openapi-code-sample-generator/internal/types"
"github.com/getkin/kin-openapi/openapi3"
)
var ErrMissingEncoder = errors.New("missing encoder")
var ErrUnknownLanguage = errors.New("language is not known")
// Templater templates a template
type Templater interface {
Template(language types.Language, endpoint *Endpoint) (*types.CodeSample, error)
}
// TemplateData holds all data available in templating
type TemplateData struct {
Parameters *types.Parameters // Different parameter types
SecurityParameters *types.Parameters // Security related parameters (authentication), their value is either "${TOKEN}" or "Bearer ${TOKEN}"
Path string // Example path
QueryParamsString string // Example query params as urlencoded string
URL string // Example URL
HTTPVerb string // HTTP Method
Body interface{} // The body as golang data type
BodyString string // The body formatted in the endpoints "accept" format Meta *types.FormattingMeta
BasicAuth bool // True if basic Auth is enabled
Additionals map[string]interface{} // Language specific data
Formatting *types.FormattingMeta // Metadata about the format used
}
// Language defines an interface for each language to be used with the templater
type Language interface {
GetAdditionals(data *TemplateData) map[string]interface{} // Allows the language to set additional data to the template data
GetTemplate() (*template.Template, error) // Must return the template for the code sample
Name() string
}
// Endpoint defines a openapi operation and meta information for templating
type Endpoint struct {
HTTPVerb string
Path string
OpenAPI struct {
Operation *openapi3.Operation
PathItem *openapi3.PathItem
Document *openapi3.T
}
}
func NewEndpoint(HTTPVerb string, path string, operation *openapi3.Operation, pathItem *openapi3.PathItem, document *openapi3.T) *Endpoint {
return &Endpoint{
HTTPVerb: HTTPVerb,
Path: path,
OpenAPI: struct {
Operation *openapi3.Operation
PathItem *openapi3.PathItem
Document *openapi3.T
}{
Operation: operation,
PathItem: pathItem,
Document: document,
},
}
}
type templater struct {
encoders map[string]types.Encoder
extractor types.Extractor
languages map[types.Language]Language
}
// NewTemplater creates a new templating instance
func NewTemplater(encoders map[string]types.Encoder, extractor types.Extractor, languages map[types.Language]Language) Templater {
return &templater{
encoders: encoders,
extractor: extractor,
languages: languages,
}
}
// Template actually templates the template
func (template *templater) Template(lang types.Language, endpoint *Endpoint) (*types.CodeSample, error) {
language, ok := template.languages[lang]
if !ok {
return nil, ErrUnknownLanguage
}
templateData, err := template.extractTemplateData(endpoint)
if err != nil {
return nil, err
}
templateData.Additionals = language.GetAdditionals(templateData)
tmpl, err := language.GetTemplate()
if err != nil {
return nil, err
}
buffer := bytes.Buffer{}
err = tmpl.Execute(&buffer, &templateData)
if err != nil {
return nil, err
}
return &types.CodeSample{
Lang: lang,
Source: buffer.String(),
Label: language.Name(),
}, nil
}
func (template *templater) extractTemplateData(endpoint *Endpoint) (*TemplateData, error) {
templateData := TemplateData{}
params, err := template.extractor.GetParameters(endpoint.OpenAPI.Operation.Parameters)
if err != nil {
return nil, err
}
secParameters, basicAuth, err := template.extractor.GetSecurity(endpoint.OpenAPI.Operation, endpoint.OpenAPI.Document)
if err != nil {
return nil, err
}
requestBodyInterface, requestBodyString, meta, err := template.extractRequestBody(endpoint.OpenAPI.Operation)
if err != nil {
return nil, err
}
url := template.extractor.GetURL(endpoint.OpenAPI.Operation, endpoint.OpenAPI.PathItem, endpoint.OpenAPI.Document)
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
url = "https://" + url
}
templateData.SecurityParameters = &secParameters // Todo digest auth seems missing
templateData.HTTPVerb = endpoint.HTTPVerb
templateData.Parameters = ¶ms
templateData.BasicAuth = basicAuth
templateData.Formatting = meta
templateData.Body = requestBodyInterface
templateData.BodyString = requestBodyString
templateData.Path = template.extractor.GetPathExample(endpoint.Path, params.Path)
templateData.URL = url
templateData.QueryParamsString = template.buildExampleQueryParams(params.Query)
// TODO scan for token
return &templateData, nil
}
func (template *templater) extractRequestBody(operation *openapi3.Operation) (interface{}, string, *types.FormattingMeta, error) {
meta := &types.FormattingMeta{}
if operation.RequestBody == nil || operation.RequestBody.Value == nil {
return nil, "", meta, nil
}
value, format, err := template.extractor.GetRequestBody(operation.RequestBody.Value)
if err != nil {
log.Warn(fmt.Sprintf("Request body parsing failed: %s", err.Error()))
return nil, "", meta, err
}
meta.Format = format
if encoder, ok := template.encoders[strings.ToLower(format)]; ok {
newValue, err := encoder.EnocdeValue(operation.RequestBody.Ref, value, meta)
if err != nil {
log.Warn(fmt.Sprintf("Request body parsing failed: %s", err.Error()))
return nil, "", meta, err
}
return value, newValue, meta, nil
}
log.Warn("Missing encoder for format: " + format)
return nil, "", meta, ErrMissingEncoder
}
func (template *templater) buildExampleQueryParams(params []*types.Parameter) string {
query := strings.Builder{}
encoder, ok := template.encoders[types.EncodingWwwUrlencode]
if !ok {
log.Warn("Missing encoder for format: " + types.EncodingWwwUrlencode)
return ""
}
for i, param := range params {
if param == nil {
continue
}
encoded, err := encoder.EnocdeParameter(param.Name, param.Value)
if err != nil {
continue
}
if i != 0 {
query.WriteString("&")
}
query.WriteString(encoded)
}
log.Debug(fmt.Sprintf("Wrote %d parameters to query", len(params)))
return query.String()
}