FetchAllPages fetches all pages from a paginated API endpoint. It returns all response bodies as a slice, stopping when a page returns an empty items array (identified by itemsKey in the JSON response).
(client *lib.APIClient, endpoint string, params map[string]string, itemsKey string)
| 222 | // It returns all response bodies as a slice, stopping when a page returns |
| 223 | // an empty items array (identified by itemsKey in the JSON response). |
| 224 | func FetchAllPages(client *lib.APIClient, endpoint string, params map[string]string, itemsKey string) ([][]byte, error) { |
| 225 | var bodies [][]byte |
| 226 | page := 1 |
| 227 | for { |
| 228 | p := make(map[string]string) |
| 229 | for k, v := range params { |
| 230 | p[k] = v |
| 231 | } |
| 232 | p["page"] = fmt.Sprintf("%d", page) |
| 233 | |
| 234 | resp, err := client.GET(endpoint, p) |
| 235 | if err != nil { |
| 236 | return bodies, err |
| 237 | } |
| 238 | if !resp.IsSuccess() { |
| 239 | return nil, fmt.Errorf("API Error (%d): %s", resp.StatusCode, resp.ParseError()) |
| 240 | } |
| 241 | bodies = append(bodies, resp.Body) |
| 242 | |
| 243 | // Check if there are items in this page |
| 244 | var raw map[string]json.RawMessage |
| 245 | if err := json.Unmarshal(resp.Body, &raw); err != nil { |
| 246 | break |
| 247 | } |
| 248 | if items, ok := raw[itemsKey]; ok { |
| 249 | var arr []json.RawMessage |
| 250 | if err := json.Unmarshal(items, &arr); err != nil || len(arr) == 0 { |
| 251 | break |
| 252 | } |
| 253 | } else { |
| 254 | break |
| 255 | } |
| 256 | |
| 257 | page++ |
| 258 | if page > 200 { // safety limit |
| 259 | break |
| 260 | } |
| 261 | } |
| 262 | return bodies, nil |
| 263 | } |
| 264 | |
| 265 | // MergePagedJSON merges multiple paginated API responses into a single JSON array. |
| 266 | // It extracts items from each page using the specified key and combines them. |