Skip to content

Commit 6116e5a

Browse files
rayjanokaRay Janoka
andauthored
Adding pagination to get records func (#21)
* adding pagination for get records * setting maxPageSize as const --------- Co-authored-by: Ray Janoka <[email protected]>
1 parent b46a2b0 commit 6116e5a

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

provider.go

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"fmt"
66
"net/http"
7+
"net/url"
78
"sync"
89

910
"github.com/libdns/libdns"
@@ -14,7 +15,7 @@ type HTTPClient interface {
1415
}
1516

1617
// Provider implements the libdns interfaces for Cloudflare.
17-
// TODO: Support pagination and retries, handle rate limits.
18+
// TODO: Support retries and handle rate limits.
1819
type Provider struct {
1920
// API tokens are used for authentication. Make sure to use
2021
// scoped API **tokens**, NOT a global API **key**.
@@ -36,20 +37,39 @@ func (p *Provider) GetRecords(ctx context.Context, zone string) ([]libdns.Record
3637
return nil, err
3738
}
3839

39-
reqURL := fmt.Sprintf("%s/zones/%s/dns_records", baseURL, zoneInfo.ID)
40-
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
41-
if err != nil {
42-
return nil, err
43-
}
40+
page := 1
41+
const maxPageSize = 100
4442

45-
var result []cfDNSRecord
46-
_, err = p.doAPIRequest(req, &result)
47-
if err != nil {
48-
return nil, err
43+
var allRecords []cfDNSRecord
44+
for {
45+
qs := make(url.Values)
46+
qs.Set("page", fmt.Sprintf("%d", page))
47+
qs.Set("per_page", fmt.Sprintf("%d", maxPageSize))
48+
reqURL := fmt.Sprintf("%s/zones/%s/dns_records?%s", baseURL, zoneInfo.ID, qs.Encode())
49+
50+
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
51+
if err != nil {
52+
return nil, err
53+
}
54+
55+
var pageRecords []cfDNSRecord
56+
response, err := p.doAPIRequest(req, &pageRecords)
57+
if err != nil {
58+
return nil, err
59+
}
60+
61+
allRecords = append(allRecords, pageRecords...)
62+
63+
lastPage := (response.ResultInfo.TotalCount + response.ResultInfo.PerPage - 1) / response.ResultInfo.PerPage
64+
if response.ResultInfo == nil || page >= lastPage || len(pageRecords) == 0 {
65+
break
66+
}
67+
68+
page++
4969
}
5070

51-
recs := make([]libdns.Record, 0, len(result))
52-
for _, rec := range result {
71+
recs := make([]libdns.Record, 0, len(allRecords))
72+
for _, rec := range allRecords {
5373
libdnsRec, err := rec.libdnsRecord(zone)
5474
if err != nil {
5575
return nil, fmt.Errorf("parsing Cloudflare DNS record %+v: %v", rec, err)

0 commit comments

Comments
 (0)