Debian Codegraph @

schema_validation/locate_schema_property.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package schema_validation
5
6 import (
7 "github.com/pb33f/jsonpath/pkg/jsonpath"
8 "github.com/pb33f/jsonpath/pkg/jsonpath/config"
9 "github.com/pb33f/libopenapi/utils"
10 "go.yaml.in/yaml/v4"
11 )
12
13 // LocateSchemaPropertyNodeByJSONPath will locate a schema property node by a JSONPath. It converts something like
14 // #/components/schemas/MySchema/properties/MyProperty to something like $.components.schemas.MySchema.properties.MyProperty
15 func LocateSchemaPropertyNodeByJSONPath(doc *yaml.Node, JSONPath string) *yaml.Node {
16 _, path := utils.ConvertComponentIdIntoFriendlyPathSearch(JSONPath)
17 return locateSchemaPropertyNode(doc, path)
18 }
19
20 func locateSchemaPropertyNode(doc *yaml.Node, path string) *yaml.Node {
21 if path == "" {
22 return nil
23 }
24 var locatedNode *yaml.Node
25 doneChan := make(chan bool)
26 locatedNodeChan := make(chan *yaml.Node)
27 go func() {
28 defer func() {
29 if err := recover(); err != nil {
30 doneChan <- true
31 }
32 }()
33 jsonPath, _ := jsonpath.NewPath(path, config.WithLazyContextTracking())
34 locatedNodes := jsonPath.Query(doc)
35 if len(locatedNodes) > 0 {
36 locatedNode = locatedNodes[0]
37 }
38 locatedNodeChan <- locatedNode
39 }()
40 select {
41 case locatedNode = <-locatedNodeChan:
42 return locatedNode
43 case <-doneChan:
44 return nil
45 }
46 }