query.gno

1.58 Kb ยท 70 lines
 1package datasource
 2
 3import "gno.land/p/demo/avl"
 4
 5// DefaultQueryRecords defines the default number of records returned by queries.
 6const DefaultQueryRecords = 50
 7
 8var defaultQuery = Query{Count: DefaultQueryRecords}
 9
10type (
11	// QueryOption configures datasource queries.
12	QueryOption func(*Query)
13
14	// Query contains datasource query options.
15	Query struct {
16		// Offset of the first record to return during iteration.
17		Offset int
18
19		// Count contains the number to records that query should return.
20		Count int
21
22		// Tag contains a tag to use as filter for the records.
23		Tag string
24
25		// Filters contains optional query filters by field value.
26		Filters avl.Tree
27	}
28)
29
30// WithOffset configures query to return records starting from an offset.
31func WithOffset(offset int) QueryOption {
32	return func(q *Query) {
33		q.Offset = offset
34	}
35}
36
37// WithCount configures the number of records that query returns.
38func WithCount(count int) QueryOption {
39	return func(q *Query) {
40		if count < 1 {
41			count = DefaultQueryRecords
42		}
43		q.Count = count
44	}
45}
46
47// ByTag configures query to filter by tag.
48func ByTag(tag string) QueryOption {
49	return func(q *Query) {
50		q.Tag = tag
51	}
52}
53
54// WithFilter assigns a new filter argument to a query.
55// This option can be used multiple times if more than one
56// filter has to be given to the query.
57func WithFilter(field string, value any) QueryOption {
58	return func(q *Query) {
59		q.Filters.Set(field, value)
60	}
61}
62
63// NewQuery creates a new datasource query.
64func NewQuery(options ...QueryOption) Query {
65	q := defaultQuery
66	for _, apply := range options {
67		apply(&q)
68	}
69	return q
70}