schemaLoader.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Copyright 2018 johandorland ( https://github.com/johandorland )
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package gojsonschema
  15. import (
  16. "bytes"
  17. "errors"
  18. "github.com/xeipuuv/gojsonreference"
  19. )
  20. // SchemaLoader is used to load schemas
  21. type SchemaLoader struct {
  22. pool *schemaPool
  23. AutoDetect bool
  24. Validate bool
  25. Draft Draft
  26. }
  27. // NewSchemaLoader creates a new NewSchemaLoader
  28. func NewSchemaLoader() *SchemaLoader {
  29. ps := &SchemaLoader{
  30. pool: &schemaPool{
  31. schemaPoolDocuments: make(map[string]*schemaPoolDocument),
  32. },
  33. AutoDetect: true,
  34. Validate: false,
  35. Draft: Hybrid,
  36. }
  37. ps.pool.autoDetect = &ps.AutoDetect
  38. return ps
  39. }
  40. func (sl *SchemaLoader) validateMetaschema(documentNode interface{}) error {
  41. var (
  42. schema string
  43. err error
  44. )
  45. if sl.AutoDetect {
  46. schema, _, err = parseSchemaURL(documentNode)
  47. if err != nil {
  48. return err
  49. }
  50. }
  51. // If no explicit "$schema" is used, use the default metaschema associated with the draft used
  52. if schema == "" {
  53. if sl.Draft == Hybrid {
  54. return nil
  55. }
  56. schema = drafts.GetSchemaURL(sl.Draft)
  57. }
  58. //Disable validation when loading the metaschema to prevent an infinite recursive loop
  59. sl.Validate = false
  60. metaSchema, err := sl.Compile(NewReferenceLoader(schema))
  61. if err != nil {
  62. return err
  63. }
  64. sl.Validate = true
  65. result := metaSchema.validateDocument(documentNode)
  66. if !result.Valid() {
  67. var res bytes.Buffer
  68. for _, err := range result.Errors() {
  69. res.WriteString(err.String())
  70. res.WriteString("\n")
  71. }
  72. return errors.New(res.String())
  73. }
  74. return nil
  75. }
  76. // AddSchemas adds an arbritrary amount of schemas to the schema cache. As this function does not require
  77. // an explicit URL, every schema should contain an $id, so that it can be referenced by the main schema
  78. func (sl *SchemaLoader) AddSchemas(loaders ...JSONLoader) error {
  79. emptyRef, _ := gojsonreference.NewJsonReference("")
  80. for _, loader := range loaders {
  81. doc, err := loader.LoadJSON()
  82. if err != nil {
  83. return err
  84. }
  85. if sl.Validate {
  86. if err := sl.validateMetaschema(doc); err != nil {
  87. return err
  88. }
  89. }
  90. // Directly use the Recursive function, so that it get only added to the schema pool by $id
  91. // and not by the ref of the document as it's empty
  92. if err = sl.pool.parseReferences(doc, emptyRef, false); err != nil {
  93. return err
  94. }
  95. }
  96. return nil
  97. }
  98. //AddSchema adds a schema under the provided URL to the schema cache
  99. func (sl *SchemaLoader) AddSchema(url string, loader JSONLoader) error {
  100. ref, err := gojsonreference.NewJsonReference(url)
  101. if err != nil {
  102. return err
  103. }
  104. doc, err := loader.LoadJSON()
  105. if err != nil {
  106. return err
  107. }
  108. if sl.Validate {
  109. if err := sl.validateMetaschema(doc); err != nil {
  110. return err
  111. }
  112. }
  113. return sl.pool.parseReferences(doc, ref, true)
  114. }
  115. // Compile loads and compiles a schema
  116. func (sl *SchemaLoader) Compile(rootSchema JSONLoader) (*Schema, error) {
  117. ref, err := rootSchema.JsonReference()
  118. if err != nil {
  119. return nil, err
  120. }
  121. d := Schema{}
  122. d.pool = sl.pool
  123. d.pool.jsonLoaderFactory = rootSchema.LoaderFactory()
  124. d.documentReference = ref
  125. d.referencePool = newSchemaReferencePool()
  126. var doc interface{}
  127. if ref.String() != "" {
  128. // Get document from schema pool
  129. spd, err := d.pool.GetDocument(d.documentReference)
  130. if err != nil {
  131. return nil, err
  132. }
  133. doc = spd.Document
  134. } else {
  135. // Load JSON directly
  136. doc, err = rootSchema.LoadJSON()
  137. if err != nil {
  138. return nil, err
  139. }
  140. // References need only be parsed if loading JSON directly
  141. // as pool.GetDocument already does this for us if loading by reference
  142. err = sl.pool.parseReferences(doc, ref, true)
  143. if err != nil {
  144. return nil, err
  145. }
  146. }
  147. if sl.Validate {
  148. if err := sl.validateMetaschema(doc); err != nil {
  149. return nil, err
  150. }
  151. }
  152. draft := sl.Draft
  153. if sl.AutoDetect {
  154. _, detectedDraft, err := parseSchemaURL(doc)
  155. if err != nil {
  156. return nil, err
  157. }
  158. if detectedDraft != nil {
  159. draft = *detectedDraft
  160. }
  161. }
  162. err = d.parse(doc, draft)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return &d, nil
  167. }