-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils-query.go
94 lines (74 loc) · 1.76 KB
/
utils-query.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/dstotijn/go-notion"
"golang.org/x/time/rate"
)
type QueryBuilder struct {
Date string // default date or start date
Today string
Title string
}
type DatabaseQuery struct {
Client *notion.Client
DatabaseID string
Query *notion.DatabaseQuery
}
func NewDatabaseQuery(c *notion.Client, databaseID string) *DatabaseQuery {
return &DatabaseQuery{
Client: c,
DatabaseID: databaseID,
Query: ¬ion.DatabaseQuery{},
}
}
func (q *DatabaseQuery) SetQuery(queryTmpl string, builder QueryBuilder) error {
if queryTmpl == "" {
return nil
}
queryData, err := Tmpl("DatabaseQuery", queryTmpl, builder)
if err != nil {
return err
}
if err := json.Unmarshal(queryData, q.Query); err != nil {
return fmt.Errorf("unmarshal DatabaseQuery: %w", err)
}
return nil
}
func (q *DatabaseQuery) Go(ctx context.Context, size int, rateLimiter ...*rate.Limiter) (chan []notion.Page, chan error) {
pagesChan := make(chan []notion.Page, size)
errChan := make(chan error, 1)
go func() {
cursor := ""
for {
if len(rateLimiter) == 1 {
rateLimiter[0].Wait(context.Background())
}
q.Query.StartCursor = cursor
resp, err := q.Client.QueryDatabase(ctx, q.DatabaseID, q.Query)
if err != nil {
errChan <- err
break
}
pagesChan <- resp.Results
if q.Query.PageSize > 0 { // hack detection to exit
break
}
if resp.HasMore {
cursor = *resp.NextCursor
} else {
break
}
}
close(pagesChan)
}()
return pagesChan, errChan
}
func (q *DatabaseQuery) Once(ctx context.Context) ([]notion.Page, error) {
resp, err := q.Client.QueryDatabase(ctx, q.DatabaseID, q.Query)
if err != nil {
return []notion.Page{}, err
}
return resp.Results, nil
}