-
Notifications
You must be signed in to change notification settings - Fork 0
/
translator.go
409 lines (388 loc) · 9.72 KB
/
translator.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
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
403
404
405
406
407
408
409
package jsonschema2openapi
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/jmoiron/jsonq"
)
// PutSchemaIntoOpenAPI returns OpenAPI spec based on template and JSONSchema which is added to its components/schemas
func PutSchemaIntoOpenAPI(schemaJSON, openAPITemplate string) (string, error) {
var schema map[string]interface{}
err := json.Unmarshal([]byte(schemaJSON), &schema)
if err != nil {
return "", fmt.Errorf("Error %s. Was not able to parse JSON schema", err.Error())
}
// Load OpenAPI spec from string constant
var tmpl map[string]interface{}
err = json.Unmarshal([]byte(openAPITemplate), &tmpl)
if err != nil {
return "", fmt.Errorf("Error %s. Not able to parse OpenAPI template", err.Error())
}
// Get componets.schemas object to fill up
jq := jsonq.NewQuery(tmpl)
schemas, err := jq.Object("components", "schemas")
if err != nil {
return "", fmt.Errorf("Error %s. Bad JSON template, no component.schemas object", err.Error())
}
// Now add definitions from our schema to that OpenAPI
schema4OpenAPI := schema["definitions"].(map[string]interface{})
for k, v := range TranslateDefinitions(schema4OpenAPI) {
schemas[k] = v
}
// And output what we got
res, _ := json.MarshalIndent(tmpl, "", " ")
return string(res), nil
}
// TranslateDefinitions translates JSON Schema definitons object to components/schemas of OpenAPI
func TranslateDefinitions(definitions map[string]interface{}) map[string]interface{} {
schema4OpenAPI := replaceRefs(
definitions,
"#/definitions/", "#/components/schemas/",
).(map[string]interface{})
schema4OpenAPI = replaceNullable(schema4OpenAPI).(map[string]interface{})
schema4OpenAPI = discriminate(schema4OpenAPI).(map[string]interface{})
return materialImplication(schema4OpenAPI).(map[string]interface{})
}
// Recursively replace old substring to new in any value of $ref key in json
func replaceRefs(jsonData interface{}, old, new string) interface{} {
switch jsonData.(type) {
case map[string]interface{}:
res := make(map[string]interface{})
for k, v := range jsonData.(map[string]interface{}) {
if k == "$ref" { // if schema has $ref
return map[string]interface{}{ // we do not need any other fields there
"$ref": strings.Replace(v.(string), old, new, 1),
}
}
res[k] = replaceRefs(v, old, new)
}
return res
case []interface{}:
res := make([]interface{}, 0)
for _, v := range jsonData.([]interface{}) {
res = append(res, replaceRefs(v, old, new))
}
return res
default:
}
return jsonData
}
// discriminate replaces any occurences of
//
// "oneOf": [
// {
// "if": { "properties": { "PROPERTY": { "enum": [ "CASE1" ] } } },
// "then": { "$ref": "REF1" }
// "else": { "properties": { "PROPERTY": { "enum": [ "CASE1" ] } } }
// },
// {
// "if": { "properties": { "PROPERTY": { "enum": [ "CASE2" ] } } },
// "then": { "$ref": "REF2" }
// "else": { "properties": { "PROPERTY": { "enum": [ "CASE2" ] } } }
// }
// ]
//
// with
//
// "oneOf": [
// { "$ref": "REF1" },
// { "$ref": "REF2" },
// ],
// "discriminator": {
// "propertyName": "PROPERTY",
// "mapping": {
// "CASE1": "REF1",
// "CASE2": "REF2"
// }
// }
//
func discriminate(jsonData interface{}) interface{} {
switch v := jsonData.(type) {
case map[string]interface{}:
ok, cases := getCases(v)
if ok {
v["oneOf"] = reflist(cases.Refs)
discriminator := make(map[string]interface{})
discriminator["propertyName"] = cases.Property
discriminator["mapping"] = cases2refmapping(cases.Cases, cases.Refs)
v["discriminator"] = discriminator
} else { // Go deeper
for k, subschema := range v {
v[k] = discriminate(subschema)
}
}
return v
case []interface{}:
res := make([]interface{}, 0)
for _, elem := range v {
res = append(res, discriminate(elem))
}
return res
default:
return v
}
}
// https://en.wikipedia.org/wiki/Material_implication_(rule_of_inference)
// Turn
// {
// "if": CONDITION
// "then": SCHEMA1
// "else": SCHEMA2
// }
//
// To
//
// {
// "anyOf": [
// { "allOf": [ CONDITION, SCHEMA1 ] },
// { "allOf": [ {"not": CONDITION }, SCHEMA2 ] }
// ]
// }
func materialImplication(jsonData interface{}) interface{} {
switch v := jsonData.(type) {
case map[string]interface{}:
ok, ifschema, thenschema, elseschema := getCondition(v)
if ok {
v["anyOf"] = []interface{}{
map[string][]interface{}{
"allOf": []interface{}{
ifschema, thenschema,
},
},
map[string][]interface{}{
"allOf": []interface{}{
map[string]interface{}{
"not": ifschema,
},
elseschema,
},
},
}
delete(v, "if")
delete(v, "then")
delete(v, "else")
} else { // Go deeper
for k, subschema := range v {
v[k] = materialImplication(subschema)
}
}
return v
case []interface{}:
res := make([]interface{}, 0)
for _, elem := range v {
res = append(res, materialImplication(elem))
}
return res
default:
return v
}
}
func getCondition(jsonData interface{}) (ok bool, ifschema, thenschema, elseschema interface{}) {
obj, ok := jsonData.(map[string]interface{})
if !ok {
return
}
ok = false
jq := jsonq.NewQuery(obj)
ifschema, err := jq.Object("if")
if err != nil {
return
}
thenschema, err = jq.Object("then")
if err != nil {
return
}
elseschema, err = jq.Object("else")
if err != nil {
return
}
ok = true
return
}
// ["a", "b"], ["A", "B"] => {"a": "A", "b":"B"}
func cases2refmapping(cases, refs []string) map[string]string {
res := make(map[string]string)
for i, ref := range refs {
res[cases[i]] = ref
}
return res
}
// ["a", "b"] => [{"$ref": "a"}, {"$ref": "b"}]
func reflist(refs []string) []map[string]string {
res := make([]map[string]string, len(refs))
for i, r := range refs {
res[i] = map[string]string{
"$ref": r,
}
}
return res
}
// casesResult is struct to hold data from cases pattern in JSON
type casesResult struct {
Property string
Cases []string
Refs []string
}
// getCases checks if JSON matches oneOf pattern described in comment for discriminate
// Returns ok true in case of match, name of property to discriminate by, and list of cases and respective references
func getCases(jsonData interface{}) (ok bool, res casesResult) {
obj, ok := jsonData.(map[string]interface{})
if !ok {
return
}
jq := jsonq.NewQuery(obj)
oneOf, err := jq.Array("oneOf")
if err != nil {
return false, res
}
if len(oneOf) < 1 {
return false, res
}
for _, caseIface := range oneOf {
ok, name, value, ref := getCase(caseIface)
if !ok {
return false, res
}
if res.Property != "" && res.Property != name {
// Properties are different in different oneOf cases
return false, res
}
res.Property = name
res.Cases = append(res.Cases, value)
res.Refs = append(res.Refs, ref)
}
if res.Property == "" { // No cycle iterations happened above
return false, res
}
return true, res
}
func getCase(jsonData interface{}) (ok bool, name, value, ref string) {
ok, ifschema, thenschema, elseschema := getCondition(jsonData)
if !ok {
return
}
ok, name, value = getConstant(ifschema)
if !ok {
return
}
ok = false
if !reflect.DeepEqual(ifschema, elseschema) {
return // else schema should equal condition schema, to always fail in else
}
ok, ref = getRef(thenschema)
return
}
// getRef checks if JSON matches { "$ref": "REF"}
// and returns match result, and REF value
func getRef(jsonData interface{}) (ok bool, ref string) {
obj, ok := jsonData.(map[string]interface{})
if !ok {
return false, ""
}
jq := jsonq.NewQuery(obj)
ref, err := jq.String("$ref")
if err != nil {
return false, ""
}
return true, ref
}
// getConstant checks if JSON matches pattern { "properties": { "PROPERTY": { "enum": [ "CASE1" ] } } }
// and returns match result, constant name and value
func getConstant(jsonData interface{}) (ok bool, name string, value string) {
obj, ok := jsonData.(map[string]interface{})
if !ok {
return false, "", ""
}
jq := jsonq.NewQuery(obj)
properties, err := jq.Object("properties")
if err != nil {
return false, "", ""
}
for k, v := range properties {
if name != "" {
return false, "", "" // properties have more than one property
}
name = k
enum, ok := v.(map[string]interface{})
if !ok {
return false, "", ""
}
casesIface, ok := enum["enum"]
if !ok {
return false, "", ""
}
cases, ok := casesIface.([]interface{})
if !ok || (len(cases) != 1) {
return false, "", ""
}
value, ok = cases[0].(string)
if !ok {
return false, "", ""
}
}
return true, name, value
}
// Recursively replace "oneOf": [{"type": X}, {"type": "null"}]
// with "type": X, "nullable": true
func replaceNullable(jsonData interface{}) interface{} {
switch jsonData.(type) {
case map[string]interface{}:
res := make(map[string]interface{})
for k, v := range jsonData.(map[string]interface{}) {
nullableType := isNullable(v)
if k == "oneOf" && nullableType != "" {
res["type"] = nullableType
res["nullable"] = true
} else {
res[k] = replaceNullable(v)
}
}
return res
case []interface{}:
res := make([]interface{}, 0)
for _, v := range jsonData.([]interface{}) {
res = append(res, replaceNullable(v))
}
return res
default:
}
return jsonData
}
// Check if json is of the form [{"type": X}, {"type": "null"}]
// and return type that is nullable
// Otherwise return empty string
func isNullable(jsonData interface{}) string {
js, ok := jsonData.([]interface{})
if !ok { // not an array
return ""
}
if len(js) != 2 {
return ""
}
res := ""
nulled := false
for _, v := range js {
typeDeclaration, ok := v.(map[string]interface{})
if !ok {
return ""
}
tIf, ok := typeDeclaration["type"]
if !ok {
return ""
}
t, ok := tIf.(string)
if !ok {
return ""
}
if t == "null" {
nulled = true
} else {
res = t
}
}
if !nulled {
return ""
}
return res
}