-
Notifications
You must be signed in to change notification settings - Fork 4
/
option.go
88 lines (71 loc) · 2.12 KB
/
option.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
package types
import (
"fmt"
"github.com/dave/jennifer/jen"
"github.com/dipdup-net/go-lib/tzkt/api"
"github.com/pkg/errors"
)
// Option -
type Option struct{}
// AsField -
func (Option) AsField(name, path string, schema api.JSONSchema, isRequired bool, result *ContractTypeResult) (jen.Code, error) {
tags := map[string]string{
"json": fmt.Sprintf("%s,omitempty", name),
}
if isRequired {
tags["validate"] = TagRequired
}
return jen.Id(fieldName("Option", name)).Op("[]").Add(jen.Id(result.GetName("Option", name))).Tag(tags), nil
}
// AsCode -
func (opt Option) AsCode(name, path string, schema api.JSONSchema, result *ContractTypeResult) (Code, error) {
optType, err := opt.createOption(name, path, schema, result)
if err != nil {
return Code{}, err
}
statement := jen.Comment(optType.Name).Line().Type().Id(optType.Name)
return Code{
Statement: statement.Add(optType.Statement),
Name: optType.Name,
}, nil
}
// AsType -
func (opt Option) AsType(name, path string, schema api.JSONSchema, result *ContractTypeResult) (Code, error) {
return opt.createOption(name, path, schema, result)
}
func (Option) createOption(name, path string, schema api.JSONSchema, result *ContractTypeResult) (Code, error) {
var code Code
code.Name = result.GetName("Option", name)
if len(schema.OneOf) != 2 {
return code, errors.Errorf("invalid oneOf field for option: %s", code.Name)
}
var entityType api.JSONSchema
for i := range schema.OneOf {
switch schema.OneOf[i].Type {
case "null":
default:
entityType = schema.OneOf[i]
}
}
newPath := getPath(path, name)
option, err := selectType(entityType)
if err != nil {
return code, err
}
optType, err := option.AsType(fmt.Sprintf("%s_option", name), newPath, entityType, result)
if err != nil {
return code, err
}
statement := jen.Op("*").Add(optType.Statement)
if !isSimpleType(entityType.Comment) {
optCode, err := option.AsCode(fmt.Sprintf("%s_option", name), newPath, entityType, result)
if err != nil {
return code, err
}
statement = statement.Add(optCode.Statement)
}
return Code{
Statement: statement.Line(),
Name: code.Name,
}, nil
}