-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-schema.go
More file actions
89 lines (79 loc) · 1.9 KB
/
json-schema.go
File metadata and controls
89 lines (79 loc) · 1.9 KB
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
package schema
import (
"encoding/json"
)
// JSONSchemaGenerator interface for types that can generate JSON Schema
type JSONSchemaGenerator interface {
JSON() map[string]interface{}
}
// JSONSchema converts any schema to JSONSchema Schema format
func JSONSchema(s JSONSchemaGenerator) map[string]interface{} {
return s.JSON()
}
// JSON converts any schema to JSON Schema bytes
func JSON(s JSONSchemaGenerator) ([]byte, error) {
schema := s.JSON()
return json.MarshalIndent(schema, "", " ")
}
// Helper functions for common JSON Schema patterns
// baseJSONSchema creates a basic JSON Schema with type
func baseJSONSchema(schemaType string) map[string]interface{} {
return map[string]interface{}{
"type": schemaType,
}
}
// addOptionalField adds a field to JSON Schema if value is not nil
func addOptionalField(schema map[string]interface{}, key string, value interface{}) {
if value != nil {
// Handle pointer types
switch v := value.(type) {
case *string:
if v != nil {
schema[key] = *v
}
case *int:
if v != nil {
schema[key] = *v
}
case *int64:
if v != nil {
schema[key] = *v
}
case *float64:
if v != nil {
schema[key] = *v
}
case *bool:
if v != nil {
schema[key] = *v
}
default:
schema[key] = value
}
}
}
// addOptionalArray adds an array field to JSON Schema if slice is not empty
func addOptionalArray(schema map[string]interface{}, key string, value interface{}) {
switch v := value.(type) {
case []string:
if len(v) > 0 {
schema[key] = v
}
case []interface{}:
if len(v) > 0 {
schema[key] = v
}
}
}
// addTitle adds title if not empty
func addTitle(schema map[string]interface{}, title string) {
if title != "" {
schema["title"] = title
}
}
// addDescription adds description if not empty
func addDescription(schema map[string]interface{}, description string) {
if description != "" {
schema["description"] = description
}
}