...
1 package jsonschema
2
3 import (
4 "context"
5 "fmt"
6 "strings"
7 )
8
9 var sr *SchemaRegistry
10
11
12
13 type SchemaRegistry struct {
14 schemaLookup map[string]*Schema
15 contextLookup map[string]*Schema
16 }
17
18
19 func GetSchemaRegistry() *SchemaRegistry {
20 if sr == nil {
21 sr = &SchemaRegistry{
22 schemaLookup: map[string]*Schema{},
23 contextLookup: map[string]*Schema{},
24 }
25 }
26 return sr
27 }
28
29
30 func ResetSchemaRegistry() {
31 sr = nil
32 }
33
34
35 func (sr *SchemaRegistry) Get(ctx context.Context, uri string) *Schema {
36 uri = strings.TrimRight(uri, "#")
37 schema := sr.schemaLookup[uri]
38 if schema == nil {
39 fetchedSchema := &Schema{}
40 err := FetchSchema(ctx, uri, fetchedSchema)
41 if err != nil {
42 schemaDebug(fmt.Sprintf("[SchemaRegistry] Fetch error: %s", err.Error()))
43 return nil
44 }
45 if fetchedSchema == nil {
46 return nil
47 }
48 fetchedSchema.docPath = uri
49
50 schema = fetchedSchema
51 sr.schemaLookup[uri] = schema
52 }
53 return schema
54 }
55
56
57 func (sr *SchemaRegistry) GetKnown(uri string) *Schema {
58 uri = strings.TrimRight(uri, "#")
59 return sr.schemaLookup[uri]
60 }
61
62
63 func (sr *SchemaRegistry) GetLocal(uri string) *Schema {
64 uri = strings.TrimRight(uri, "#")
65 return sr.contextLookup[uri]
66 }
67
68
69 func (sr *SchemaRegistry) Register(sch *Schema) {
70 if sch.docPath == "" {
71 return
72 }
73 sr.schemaLookup[sch.docPath] = sch
74 }
75
76
77 func (sr *SchemaRegistry) RegisterLocal(sch *Schema) {
78 if sch.id != "" && IsLocalSchemaID(sch.id) {
79 sr.contextLookup[sch.id] = sch
80 }
81
82 if sch.HasKeyword("$anchor") {
83 anchorKeyword := sch.keywords["$anchor"].(*Anchor)
84 anchorURI := sch.docPath + "#" + string(*anchorKeyword)
85 if sr.contextLookup == nil {
86 sr.contextLookup = map[string]*Schema{}
87 }
88 sr.contextLookup[anchorURI] = sch
89 }
90 }
91
View as plain text