-
Notifications
You must be signed in to change notification settings - Fork 4
/
parser.go
409 lines (390 loc) · 11.4 KB
/
parser.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 main
import (
"net/url"
"sort"
"strings"
"github.com/achiku/varfmt"
"github.com/lestrrat-go/go-jsval/builder"
hschema "github.com/lestrrat-go/jshschema"
schema "github.com/lestrrat-go/jsschema"
"github.com/lestrrat-go/jsval"
"github.com/pkg/errors"
)
// PropType proper type
type PropType int
// Property types
const (
PropTypeScalar PropType = iota
PropTypeArray
PropTypeObject
)
// Parser convertor
type Parser struct {
schema *schema.Schema
pkgName string
}
// NewParser creates parser
func NewParser(sh *schema.Schema, pkgName string) *Parser {
return &Parser{
schema: sh,
pkgName: pkgName,
}
}
func resolveSchema(sch *schema.Schema, root *schema.Schema) (*schema.Schema, error) {
if sch.IsResolved() {
return sch, nil
}
sh, err := sch.Resolve(root)
if err != nil {
return nil, err
}
// FIXME: recursively resolving schema. may need to limit # of recursion.
return resolveSchema(sh, root)
}
func typesToStrings(types schema.PrimitiveTypes) []string {
var vals []string
for _, tt := range types {
vals = append(vals, tt.String())
}
return vals
}
func sortProperties(props []*Property) []*Property {
pMap := make(map[string]*Property)
for _, p := range props {
pMap[p.Name] = p
}
var names []string
for n := range pMap {
names = append(names, n)
}
sort.Strings(names)
var sorted []*Property
for _, n := range names {
sorted = append(sorted, pMap[n])
}
return sorted
}
func sortActions(acs []Action) []Action {
aMap := make(map[string]Action)
for _, a := range acs {
aMap[a.Method+a.Href] = a
}
var refs []string
for r := range aMap {
refs = append(refs, r)
}
sort.Strings(refs)
var sorted []Action
for _, r := range refs {
sorted = append(sorted, aMap[r])
}
return sorted
}
func sortValidator(vals []*jsval.JSVal) []*jsval.JSVal {
vMap := make(map[string]*jsval.JSVal)
for _, v := range vals {
vMap[v.Name] = v
}
var names []string
for n := range vMap {
names = append(names, n)
}
sort.Strings(names)
var sorted []*jsval.JSVal
for _, n := range names {
sorted = append(sorted, vMap[n])
}
return sorted
}
// NewProperty new property
func NewProperty(name string, tp *schema.Schema, df *schema.Schema, root *schema.Schema) (*Property, error) {
// save reference before resolving ref
ref := tp.Reference
fieldSchema, err := resolveSchema(tp, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve, %s", name)
}
fld := &Property{
Name: name,
Format: string(fieldSchema.Format),
Types: fieldSchema.Type,
Required: df.IsPropRequired(name),
Pattern: fieldSchema.Pattern,
Reference: ref,
Schema: fieldSchema,
}
switch {
case fieldSchema.Type.Contains(schema.ArrayType):
// if this field is an array
// currently this tool supports only one itme per array field
if len(fieldSchema.Items.Schemas) != 1 {
return nil, errors.Errorf("array type has to have an item: %s", name)
}
item := fieldSchema.Items.Schemas[0]
resolvedItem, err := resolveSchema(item, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve: %s", name)
}
switch {
case isMainResource(item.Reference) && resolvedItem.Type.Contains(schema.ObjectType):
// reference to main resource object
// log.Printf("ref to main resource: %s: %s", name, item.Reference)
fld.SecondTypes = []schema.PrimitiveType{schema.ObjectType}
fld.SecondReference = item.Reference
case item.Properties == nil && fieldSchema.Properties != nil:
// field schema already has properties = inline object
// log.Printf("inline obj: %s: %v", name, fieldSchema.Properties)
var inlineFields []*Property
for k, prop := range fieldSchema.Properties {
f, err := NewProperty(k, prop, df, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to perse inline object: %s", k)
}
inlineFields = append(inlineFields, f)
}
fld.InlineProperties = inlineFields
fld.SecondTypes = []schema.PrimitiveType{schema.ObjectType}
case item.Reference == "" && item.Properties == nil:
// no reference, no item properties = primitive type
// log.Printf("primitive type: %s %s", name, item.Type)
fld.SecondTypes = item.Type
case item.Reference != "" && !resolvedItem.Type.Contains(schema.ObjectType):
// reference to primitive = resolved primitive type
// log.Printf("resolved primitive type: %s %s", name, resolvedItem.Type)
fld.SecondTypes = resolvedItem.Type
case item.Reference == "" && item.Properties != nil:
// no reference, item properties = inline object
// parse properties, and recursively create inline fields
// log.Printf("resolved inline obj: %s: %v", name, item.Properties)
var inlineFields []*Property
for k, prop := range item.Properties {
f, err := NewProperty(k, prop, df, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to perse inline object: %s", k)
}
inlineFields = append(inlineFields, f)
}
fld.InlineProperties = inlineFields
fld.SecondTypes = []schema.PrimitiveType{schema.ObjectType}
case !isMainResource(item.Reference):
// log.Printf("resolved inline obj: %s: %v", name, resolvedItem.Properties)
var inlineFields []*Property
for k, prop := range resolvedItem.Properties {
f, err := NewProperty(k, prop, df, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to perse inline object: %s", k)
}
inlineFields = append(inlineFields, f)
}
fld.InlineProperties = inlineFields
fld.SecondTypes = []schema.PrimitiveType{schema.ObjectType}
}
fld.PropType = PropTypeArray
case fieldSchema.Type.Contains(schema.ObjectType):
// if this field is a object
switch {
case fieldSchema.Reference == "" && fieldSchema.Properties != nil:
// inline object without definitions
var inlineFields []*Property
for k, prop := range fieldSchema.Properties {
f, err := NewProperty(k, prop, df, root)
if err != nil {
return nil, errors.Wrapf(err, "failed to perse inline object: %s", k)
}
inlineFields = append(inlineFields, f)
}
fld.InlineProperties = inlineFields
}
fld.PropType = PropTypeObject
default:
// if this field is a scalar
fld.PropType = PropTypeScalar
}
return fld, nil
}
// ParseValidators parse validator
func (p *Parser) ParseValidators() (Validators, error) {
vals := make(Validators)
for _, df := range p.schema.Definitions {
for name, tp := range df.Properties {
fs, err := resolveSchema(tp, p.schema)
if err != nil {
return nil, err
}
if fs.Pattern != nil &&
!fs.Type.Contains(schema.ObjectType) && !fs.Type.Contains(schema.ArrayType) {
v := Validator{
Name: name,
RegexpString: fs.Pattern.String(),
}
vals[name] = v
}
}
}
return vals, nil
}
// ParseResources parse plain resource
func (p *Parser) ParseResources() (map[string]Resource, error) {
res := make(map[string]Resource)
// parse resource itself
for id, df := range p.schema.Definitions {
rs := Resource{
Name: id,
Title: df.Title,
Schema: df,
IsPrimary: true,
}
// parse resource field
var flds []*Property
for name, tp := range df.Properties {
fld, err := NewProperty(name, tp, df, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", id)
}
fld.InlineProperties = sortProperties(fld.InlineProperties)
flds = append(flds, fld)
}
rs.Properties = sortProperties(flds)
res[id] = rs
}
return res, nil
}
// ParseActions parse endpoints
func (p *Parser) ParseActions(res map[string]Resource) (map[string][]Action, error) {
eptsMap := make(map[string][]Action)
for id, df := range p.schema.Definitions {
// use json hyper schema to parse links
hsc := hschema.New()
if err := hsc.Extract(df.Extras); err != nil {
return nil, errors.Wrapf(err, "failed to extract links for (%s)", id)
}
// parse endpoints
var eps []Action
for _, e := range hsc.Links {
href, err := url.QueryUnescape(e.Href)
if err != nil {
return nil, errors.Wrapf(err, "failed to unescape %s", e.Href)
}
var encoding string
if e.EncType == "" {
encoding = "application/json"
} else {
encoding = e.EncType
}
ep := Action{
Encoding: encoding,
Href: href,
Method: e.Method,
Title: e.Title,
Rel: e.Rel,
}
// parse request if exists
if e.Schema != nil {
var flds []*Property
for name, tp := range e.Schema.Properties {
fld, err := NewProperty(name, tp, e.Schema, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", id)
}
flds = append(flds, fld)
}
ep.Request = &Resource{
Name: id,
Properties: sortProperties(flds),
Title: e.Schema.Title,
IsPrimary: false,
}
}
// parse response if exists
if e.TargetSchema != nil {
// http://json-schema.org/latest/json-schema-hypermedia.html#rfc.section.5.4
switch {
case e.TargetSchema.Reference == "":
var flds []*Property
for name, tp := range e.TargetSchema.Properties {
fld, err := NewProperty(name, tp, df, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", id)
}
flds = append(flds, fld)
}
ep.Response = &Resource{
Name: id,
Properties: sortProperties(flds),
Title: e.TargetSchema.Title,
Schema: e.TargetSchema,
IsPrimary: false,
}
case e.TargetSchema.Reference != "" && IsRefToMainResource(e.TargetSchema.Reference):
ep.Response = &Resource{
Name: id,
Title: e.TargetSchema.Title,
Schema: e.TargetSchema,
IsPrimary: false,
}
case e.TargetSchema.Reference != "" && !IsRefToMainResource(e.TargetSchema.Reference):
fld, err := NewProperty(e.TargetSchema.ID, e.TargetSchema, df, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", id)
}
ep.Response = &Resource{
Name: id,
Properties: sortProperties(fld.InlineProperties),
Title: e.TargetSchema.Title,
Schema: e.TargetSchema,
IsPrimary: false,
}
}
} else {
// if targetSchema is not set, use default resource for this link
resp, ok := res[id]
if !ok {
return nil, errors.Errorf("resource not found: %s", id)
}
ep.Response = &resp
}
eps = append(eps, ep)
}
eptsMap[id] = sortActions(eps)
}
return eptsMap, nil
}
// ParseJsValValidators parse validator
func (p *Parser) ParseJsValValidators() ([]*jsval.JSVal, error) {
var validators []*jsval.JSVal
for id, df := range p.schema.Definitions {
// use json hyper schema to parse links
hsc := hschema.New()
if err := hsc.Extract(df.Extras); err != nil {
return nil, errors.Wrapf(err, "failed to extract links for (%s)", id)
}
for _, e := range hsc.Links {
var v *jsval.JSVal
if e.Schema == nil {
v = jsval.New()
v.SetRoot(jsval.Any())
} else {
sh, err := resolveSchema(e.Schema, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to resolve, %s", id)
}
b := builder.New()
v, err = b.BuildWithCtx(sh, p.schema)
if err != nil {
return nil, errors.Wrapf(err, "failed to build validator: %s", id)
}
}
v.Name = varfmt.PublicVarName(
strings.Replace(id+strings.Title(e.Rel), "-", "_", -1) + "Validator")
validators = append(validators, v)
}
}
return sortValidator(validators), nil
}
func isMainResource(ref string) bool {
if ref == "" {
return false
}
tmp := strings.Replace(ref, "#/definitions/", "", 1)
return !strings.Contains(tmp, "/")
}