Skip to content

Commit 28c3dc6

Browse files
authored
fix(email): auto-paginate search results when limit exceeds API max (#29)
1 parent c9d6cfa commit 28c3dc6

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

internal/cli/email/search.go

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,15 @@ Examples:
5555
remainingArgs := args[1:]
5656

5757
_, err := common.WithClient(remainingArgs, func(ctx context.Context, client ports.NylasClient, grantID string) (struct{}, error) {
58+
// Auto-paginate when limit exceeds API maximum
59+
needsPagination := limit > common.MaxAPILimit
60+
apiLimit := limit
61+
if needsPagination {
62+
apiLimit = common.MaxAPILimit
63+
}
64+
5865
params := &domain.MessageQueryParams{
59-
Limit: limit,
66+
Limit: apiLimit,
6067
}
6168

6269
// Use query as subject search unless it's a wildcard
@@ -102,7 +109,30 @@ Examples:
102109
params.ReceivedBefore = t.Unix()
103110
}
104111

105-
messages, err := client.GetMessagesWithParams(ctx, grantID, params)
112+
var messages []domain.Message
113+
var err error
114+
115+
if needsPagination {
116+
fetcher := func(ctx context.Context, cursor string) (common.PageResult[domain.Message], error) {
117+
params.PageToken = cursor
118+
resp, fetchErr := client.GetMessagesWithCursor(ctx, grantID, params)
119+
if fetchErr != nil {
120+
return common.PageResult[domain.Message]{}, fetchErr
121+
}
122+
return common.PageResult[domain.Message]{
123+
Data: resp.Data,
124+
NextCursor: resp.Pagination.NextCursor,
125+
}, nil
126+
}
127+
128+
config := common.DefaultPaginationConfig()
129+
config.PageSize = apiLimit
130+
config.MaxItems = limit
131+
132+
messages, err = common.FetchAllPages(ctx, config, fetcher)
133+
} else {
134+
messages, err = client.GetMessagesWithParams(ctx, grantID, params)
135+
}
106136
if err != nil {
107137
return struct{}{}, common.WrapSearchError("messages", err)
108138
}
@@ -127,7 +157,7 @@ Examples:
127157
},
128158
}
129159

130-
cmd.Flags().IntVarP(&limit, "limit", "l", 20, "Maximum number of results")
160+
cmd.Flags().IntVarP(&limit, "limit", "l", 20, "Maximum number of results (auto-paginates if >200)")
131161
cmd.Flags().StringVar(&from, "from", "", "Filter by sender")
132162
cmd.Flags().StringVar(&to, "to", "", "Filter by recipient")
133163
cmd.Flags().StringVar(&subject, "subject", "", "Filter by subject")

0 commit comments

Comments
 (0)