forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swagger.go
259 lines (218 loc) · 7.54 KB
/
swagger.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
package main
import (
"encoding/json"
"errors"
"github.com/lonelycode/go-uuid/uuid"
"github.com/lonelycode/tykcommon"
"io/ioutil"
"strings"
)
const (
SwaggerSource APIImporterSource = "swagger"
)
type DefinitionObjectFormatAST struct {
Format string `json:"format"`
Type string `json:"type"`
}
type DefinitionObjectAST struct {
Type string `json:"type"`
Required []string `json:"required"`
Properties map[string]DefinitionObjectFormatAST `json:"properties"`
}
type ResponseCodeObjectAST struct {
Description string `json:"description"`
Schema struct {
Items map[string]interface{} `json:"items"`
Type string `json:"type"`
} `json:"schema"`
}
type PathMethodObject struct {
Description string `json:"description"`
OperationID string `json:"operationId"`
Responses map[string]ResponseCodeObjectAST `json:"responses"`
}
type PathItemObject struct {
Get PathMethodObject `json:"get"`
Put PathMethodObject `json:"put"`
Post PathMethodObject `json:"post"`
Patch PathMethodObject `json:"patch"`
Options PathMethodObject `json:"options"`
Delete PathMethodObject `json:"delete"`
Head PathMethodObject `json:"head"`
}
type SwaggerAST struct {
BasePath string `json:"basePath"`
Consumes []string `json:"consumes"`
Definitions map[string]DefinitionObjectAST `json:"definitions"`
Host string `json:"host"`
Info struct {
Contact struct {
Email string `json:"email"`
Name string `json:"name"`
URL string `json:"url"`
} `json:"contact"`
Description string `json:"description"`
License struct {
Name string `json:"name"`
URL string `json:"url"`
} `json:"license"`
TermsOfService string `json:"termsOfService"`
Title string `json:"title"`
Version string `json:"version"`
} `json:"info"`
Paths map[string]PathItemObject `json:"paths"`
Produces []string `json:"produces"`
Schemes []string `json:"schemes"`
Swagger string `json:"swagger"`
}
func (s *SwaggerAST) ReadString(asJson string) error {
marshallErr := json.Unmarshal([]byte(asJson), &s)
if marshallErr != nil {
log.Error("Marshalling failed: ", marshallErr)
return marshallErr
}
return nil
}
func (s *SwaggerAST) ConvertIntoApiVersion(asMock bool) (tykcommon.VersionInfo, error) {
thisVersionInfo := tykcommon.VersionInfo{}
if asMock {
return thisVersionInfo, errors.New("Swagger mocks not supported")
}
thisVersionInfo.UseExtendedPaths = true
thisVersionInfo.Name = s.Info.Version
thisVersionInfo.ExtendedPaths.WhiteList = make([]tykcommon.EndPointMeta, 0)
if len(s.Paths) == 0 {
return thisVersionInfo, errors.New("No paths defined in swagger file!")
}
for pathName, pathSpec := range s.Paths {
log.Debug("path: %s", pathName)
newEndpointMeta := tykcommon.EndPointMeta{}
newEndpointMeta.MethodActions = make(map[string]tykcommon.EndpointMethodMeta)
newEndpointMeta.Path = pathName
// We just want the paths here, no mocks
methods := map[string]PathMethodObject{
"GET": pathSpec.Get,
"PUT": pathSpec.Put,
"POST": pathSpec.Post,
"HEAD": pathSpec.Head,
"PATCH": pathSpec.Patch,
"OPTIONS": pathSpec.Options,
"DELETE": pathSpec.Delete,
}
for methodName, m := range methods {
// skip methods that are not defined
if len(m.Responses) == 0 && m.Description == "" && m.OperationID == "" {
continue
}
thisMethodAction := tykcommon.EndpointMethodMeta{}
thisMethodAction.Action = tykcommon.NoAction
newEndpointMeta.MethodActions[methodName] = thisMethodAction
}
thisVersionInfo.ExtendedPaths.WhiteList = append(thisVersionInfo.ExtendedPaths.WhiteList, newEndpointMeta)
}
return thisVersionInfo, nil
}
func (s *SwaggerAST) InsertIntoAPIDefinitionAsVersion(thisVersion tykcommon.VersionInfo, thisDefinition *tykcommon.APIDefinition, versionName string) error {
thisDefinition.VersionData.NotVersioned = false
thisDefinition.VersionData.Versions[versionName] = thisVersion
return nil
}
// Comand mode stuff
func handleSwaggerMode(arguments map[string]interface{}) {
doCreate := arguments["--create-api"]
inputFile := arguments["--import-swagger"]
if doCreate == true {
upstreamVal := arguments["--upstream-target"]
orgId := arguments["--org-id"]
if upstreamVal != nil && orgId != nil {
// Create the API with the blueprint
s, err := swaggerLoadFile(inputFile.(string))
if err != nil {
log.Error("File load error: ", err)
return
}
def, dErr := createDefFromSwagger(s, orgId.(string), upstreamVal.(string), arguments["--as-mock"].(bool))
if dErr != nil {
log.Error("Failed to create API Defintition from file")
return
}
printDef(def)
return
}
log.Error("No upstream target or org ID defined, these are both required")
} else {
// Different branch, here we need an API Definition to modify
forApiPath := arguments["--for-api"]
if forApiPath == nil {
log.Error("If ading to an API, the path to the defintiton must be listed")
return
}
versionName := arguments["--as-version"]
if versionName == nil {
log.Error("No version defined for this import operation, please set an import ID using the --as-version flag")
return
}
thisDefFromFile, fileErr := apiDefLoadFile(forApiPath.(string))
if fileErr != nil {
log.Error("failed to load and decode file data for API Definition: ", fileErr)
return
}
s, err := swaggerLoadFile(inputFile.(string))
if err != nil {
log.Error("File load error: ", err)
return
}
versionData, err := s.ConvertIntoApiVersion(arguments["--as-mock"].(bool))
if err != nil {
log.Error("Conversion into API Def failed: ", err)
}
insertErr := s.InsertIntoAPIDefinitionAsVersion(versionData, &thisDefFromFile, versionName.(string))
if insertErr != nil {
log.Error("Insertion failed: ", insertErr)
return
}
printDef(&thisDefFromFile)
}
}
func createDefFromSwagger(s *SwaggerAST, orgId, upstreamURL string, as_mock bool) (*tykcommon.APIDefinition, error) {
thisAD := tykcommon.APIDefinition{}
thisAD.Name = s.Info.Title
thisAD.Active = true
thisAD.UseKeylessAccess = true
thisAD.APIID = uuid.NewUUID().String()
thisAD.OrgID = orgId
thisAD.VersionDefinition.Key = "version"
thisAD.VersionDefinition.Location = "header"
thisAD.VersionData.Versions = make(map[string]tykcommon.VersionInfo)
thisAD.VersionData.NotVersioned = false
thisAD.Proxy.ListenPath = "/" + thisAD.APIID + "/"
thisAD.Proxy.StripListenPath = true
thisAD.Proxy.TargetURL = upstreamURL
if as_mock {
log.Warning("Mocks not supported for Swagger definitions, ignoring option")
}
versionData, err := s.ConvertIntoApiVersion(false)
if err != nil {
log.Error("Conversion into API Def failed: ", err)
}
s.InsertIntoAPIDefinitionAsVersion(versionData, &thisAD, strings.Trim(s.Info.Version, " "))
return &thisAD, nil
}
func swaggerLoadFile(filePath string) (*SwaggerAST, error) {
thisSwagger, astErr := GetImporterForSource(SwaggerSource)
if astErr != nil {
log.Error("Couldn't get swagger importer: ", astErr)
return thisSwagger.(*SwaggerAST), astErr
}
swaggerFileData, err := ioutil.ReadFile(filePath)
if err != nil {
log.Error("Couldn't load swagger file: ", err)
return thisSwagger.(*SwaggerAST), err
}
readErr := thisSwagger.ReadString(string(swaggerFileData))
if readErr != nil {
log.Error("Failed to decode object")
return thisSwagger.(*SwaggerAST), readErr
}
return thisSwagger.(*SwaggerAST), nil
}