aboutsummaryrefslogtreecommitdiff
path: root/model/query.go
blob: 56a0dfe22fe495c7348ec246bcd1f7d0face4587 (plain) (blame)
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
package model

import (
	"fmt"
	"strconv"
)

// Query returns node by array query
func Query(n Node, query []string) (Node, error) {
	if len(query) == 0 {
		return n, nil
	}
	head, rest := query[0], query[1:]
	switch n := 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 Query(next, rest)
	case *ObjectNode:
		next, err := n.Get(head)
		if err != nil {
			return nil, err
		}
		return Query(next, rest)
	}
	return nil, fmt.Errorf("can't get %s from node type %s", head, n.Type())
}