forked from rs/rest-layer
/
jsonschema.go
181 lines (168 loc) · 4.29 KB
/
jsonschema.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
package jsonschema
import (
"encoding/json"
"errors"
"fmt"
"github.com/rs/rest-layer/schema"
"io"
"strconv"
"strings"
)
var (
// ErrNotImplemented means schema.FieldValidator type is not implemented
ErrNotImplemented = errors.New("Schema not Implemented")
)
type errWriter struct {
w io.Writer
err error
}
func (ew errWriter) writeFormat(format string, a ...interface{}) {
if ew.err != nil {
return
}
_, ew.err = fmt.Fprintf(ew.w, format, a...)
}
func (ew errWriter) writeString(s string) {
if ew.err != nil {
return
}
_, ew.err = ew.w.Write([]byte(s))
}
func (ew errWriter) write(b []byte) {
if ew.err != nil {
return
}
_, ew.err = ew.w.Write(b)
}
// ValidatorToJSONSchema takes a validator and renders to JSON
func validatorToJSONSchema(w io.Writer, v schema.FieldValidator) (err error) {
if v == nil {
return nil
}
ew := errWriter{w: w}
switch t := v.(type) {
case *schema.String:
ew.writeString(`"type": "string"`)
if t.Regexp != "" {
ew.writeFormat(`, "pattern": %q`, t.Regexp)
}
if len(t.Allowed) > 0 {
var allowed []string
for _, value := range t.Allowed {
allowed = append(allowed, fmt.Sprintf("%q", value))
}
ew.writeFormat(`, "enum": [%s]`, strings.Join(allowed, ", "))
}
if t.MinLen > 0 {
ew.writeFormat(`, "minLength": %s`, strconv.FormatInt(int64(t.MinLen), 10))
}
if t.MaxLen > 0 {
ew.writeFormat(`, "maxLength": %s`, strconv.FormatInt(int64(t.MaxLen), 10))
}
case *schema.Integer:
ew.writeString(`"type": "integer"`)
if len(t.Allowed) > 0 {
var allowed []string
for _, value := range t.Allowed {
allowed = append(allowed, strconv.FormatInt(int64(value), 10))
}
ew.writeFormat(`, "enum": [%s]`, strings.Join(allowed, ","))
}
if t.Boundaries != nil {
ew.writeFormat(`, "minimum": %s, "maximum": %s`,
strconv.FormatFloat(t.Boundaries.Min, 'E', -1, 64),
strconv.FormatFloat(t.Boundaries.Max, 'E', -1, 64))
}
case *schema.Float:
ew.writeString(`"type": "number"`)
if len(t.Allowed) > 0 {
var allowed []string
for _, value := range t.Allowed {
allowed = append(allowed, strconv.FormatFloat(value, 'E', -1, 64))
}
ew.writeFormat(`, "enum": [%s]`, strings.Join(allowed, ","))
}
if t.Boundaries != nil {
ew.writeFormat(`, "minimum": %s, "maximum": %s`,
strconv.FormatFloat(t.Boundaries.Min, 'E', -1, 64),
strconv.FormatFloat(t.Boundaries.Max, 'E', -1, 64))
}
case *schema.Array:
ew.writeString(`"type": "array"`)
if t.ValuesValidator != nil {
ew.writeString(`, "items": `)
if ew.err == nil {
ew.err = validatorToJSONSchema(w, t.ValuesValidator)
}
}
case *schema.Object:
if ew.err == nil {
ew.err = schemaToJSONSchema(w, t.Schema)
}
case *schema.Time:
ew.writeString(`"type": "string", "format": "date-time"`)
case *schema.Bool:
ew.writeString(`"type": "boolean"`)
default:
return ErrNotImplemented
}
return ew.err
}
// SchemaToJSONSchema helper
func schemaToJSONSchema(w io.Writer, s *schema.Schema) (err error) {
ew := errWriter{w: w}
ew.writeString("{")
if s.Description != "" {
ew.writeFormat(`"title": %q, `, s.Description)
}
ew.writeString(`"type": "object", `)
ew.writeString(`"properties": {`)
var required []string
var notFirst bool
for key, field := range s.Fields {
if notFirst {
ew.writeString(", ")
}
notFirst = true
ew.writeFormat("%q: {", key)
if field.Description != "" {
ew.writeFormat(`"description": %q, `, field.Description)
}
if field.Required {
required = append(required, fmt.Sprintf("%q", key))
}
if field.ReadOnly {
ew.writeFormat(`"readOnly": %t, `, field.ReadOnly)
}
if ew.err == nil {
ew.err = validatorToJSONSchema(w, field.Validator)
}
if field.Default != nil {
b, err := json.Marshal(field.Default)
if err != nil {
return err
}
ew.writeString(`, "default": `)
ew.write(b)
}
ew.writeString("}")
if ew.err != nil {
break
}
}
ew.writeFormat(`, "required": [%s]`, strings.Join(required, ", "))
ew.writeString("}}")
return ew.err
}
// Encoder encodes schema.Schema into a JSONSchema
type Encoder struct {
io.Writer
}
// NewEncoder returns a new JSONSchema Encoder.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{w}
}
// Encode is take schema and writes to Writer
func (e *Encoder) Encode(s *schema.Schema) error {
return schemaToJSONSchema(e.Writer, s)
}