aboutsummaryrefslogtreecommitdiff
path: root/model/query.go
diff options
context:
space:
mode:
authorNeonXP <i@neonxp.dev>2022-11-16 05:11:19 +0300
committerNeonXP <i@neonxp.dev>2022-11-16 05:11:19 +0300
commita321bfe7b2f6db5078de7b2e5ed5ddcccd65f319 (patch)
treed11c187bceee610a7843463949df128569142680 /model/query.go
initial commit
Diffstat (limited to 'model/query.go')
-rw-r--r--model/query.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/model/query.go b/model/query.go
new file mode 100644
index 0000000..75ee6b0
--- /dev/null
+++ b/model/query.go
@@ -0,0 +1,33 @@
+package model
+
+import (
+ "fmt"
+ "strconv"
+)
+
+// Query returns node by array query
+func (n *Node) Query(query []string) (*Node, error) {
+ if len(query) == 0 {
+ return n, nil
+ }
+ head, rest := query[0], query[1:]
+ switch n.Type {
+ case ArrayNode:
+ idx, err := strconv.Atoi(head)
+ if err != nil {
+ return nil, fmt.Errorf("index must be a number, got %s", head)
+ }
+ next, err := n.Index(idx)
+ if err != nil {
+ return nil, err
+ }
+ return next.Query(rest)
+ case ObjectNode:
+ next, err := n.Get(head)
+ if err != nil {
+ return nil, err
+ }
+ return next.Query(rest)
+ }
+ return nil, fmt.Errorf("can't get %s from node type %s", head, n.Type)
+}