-
Notifications
You must be signed in to change notification settings - Fork 0
/
iter.go
78 lines (69 loc) · 1.45 KB
/
iter.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
package gmailext
import (
"context"
"errors"
"fmt"
"golang.org/x/sync/errgroup"
"google.golang.org/api/gmail/v1"
)
const (
limitPerRequest = 500
)
var (
errBreak = fmt.Errorf("break")
)
func Iter(
ctx context.Context,
service *gmail.Service,
userID string,
query string,
process func(context.Context, *gmail.Message) (bool, error),
) error {
messageIDs := []string{}
if err := service.Users.Messages.List(userID).
Q(query).
MaxResults(limitPerRequest).
Context(ctx).
Pages(ctx, func(res *gmail.ListMessagesResponse) error {
for _, messageSummary := range res.Messages {
messageIDs = append(messageIDs, messageSummary.Id)
}
return nil
}); err != nil {
return fmt.Errorf("list gmail messages: %w", err)
}
eg, ctx := errgroup.WithContext(ctx)
eg.SetLimit(4)
for _, messageID := range messageIDs {
messageID := messageID
eg.Go(func() error {
message, err := Get(ctx, service, userID, messageID)
if err != nil {
return fmt.Errorf("get one gmail message: %w", err)
}
next, err := process(ctx, message)
if err != nil {
return err
}
if !next {
return errBreak
}
return nil
})
}
if err := eg.Wait(); err != nil && !errors.Is(err, errBreak) {
return err
}
return nil
}
func Get(
ctx context.Context,
service *gmail.Service,
userID string,
messageID string,
) (*gmail.Message, error) {
return service.Users.Messages.Get(userID, messageID).
Format("full").
Context(ctx).
Do()
}