-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfields_parser.go
More file actions
71 lines (55 loc) · 1.58 KB
/
Copy pathfields_parser.go
File metadata and controls
71 lines (55 loc) · 1.58 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package qfv
import (
"fmt"
"strings"
)
type QFVFieldsError struct {
Field string
Message string
}
func (e *QFVFieldsError) Error() string {
if e.Field != "" {
return fmt.Sprintf("error on field '%s': %s", e.Field, e.Message)
}
return fmt.Sprintf("error: %s", e.Message)
}
// FieldsNode represents the fields part of the query
type FieldsNode struct {
Fields []string
}
func (n FieldsNode) Type() NodeType {
return NodeTypeFieldList
}
// FieldsParser parses the query parameter for fields
type FieldsParser struct {
allowedFieldsFields map[string]any // any because don't allocate memory for struct{}
}
// NewFieldsParser creates a new parser with the allowed fields
func NewFieldsParser(allowedFields []string) *FieldsParser {
fieldsFields := make(map[string]any, len(allowedFields))
for _, f := range allowedFields {
fieldsFields[f] = struct{}{}
}
return &FieldsParser{
allowedFieldsFields: fieldsFields,
}
}
// Parse parses the fields parameter
func (p *FieldsParser) Parse(input string) (FieldsNode, error) {
if input == "" {
return FieldsNode{}, &QFVFieldsError{Message: "empty input expression"}
}
parts := strings.Split(input, ",")
fields := make([]string, 0, len(parts))
for _, part := range parts {
part = strings.TrimSpace(part)
if part == "" {
return FieldsNode{}, &QFVFieldsError{Field: part, Message: "empty field expression"}
}
if _, exists := p.allowedFieldsFields[part]; !exists {
return FieldsNode{}, &QFVFieldsError{Field: part, Message: "unknown field"}
}
fields = append(fields, part)
}
return FieldsNode{Fields: fields}, nil
}