kalshi-cpp 0.6.2
C++23 client for Kalshi's Predictions API
Loading...
Searching...
No Matches
pagination.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "kalshi/error.hpp"
4
5#include <cstddef>
6#include <limits>
7#include <optional>
8#include <string>
9#include <string_view>
10#include <type_traits>
11#include <utility>
12#include <vector>
13
14namespace kalshi {
15
30template <class Fetch, class Response, class Items>
31[[nodiscard]] Result<std::vector<typename Items::value_type>>
32collect_pages(Fetch&& fetch, Items Response::*items,
33 std::size_t max_pages = std::numeric_limits<std::size_t>::max()) {
34 std::vector<typename Items::value_type> all;
35 std::string cursor;
36 for (std::size_t page = 0; page < max_pages; ++page) {
37 Result<Response> response = fetch(std::string_view{cursor});
38 if (!response) {
39 return std::unexpected(std::move(response.error()));
40 }
41 Items& batch = (*response).*items;
42 all.insert(all.end(), std::make_move_iterator(batch.begin()),
43 std::make_move_iterator(batch.end()));
44 std::string next;
45 if constexpr (std::is_same_v<decltype(response->cursor), std::optional<std::string>>) {
46 next = response->cursor.value_or("");
47 } else {
48 next = std::move(response->cursor);
49 }
50 if (next.empty()) {
51 break;
52 }
53 if (next == cursor) {
54 return std::unexpected(
55 Error{ErrorCode::ParseError, "Pagination cursor did not advance: " + next, 0, {}});
56 }
57 cursor = std::move(next);
58 }
59 return all;
60}
61
62} // namespace kalshi
Definition api.hpp:15
Result< std::vector< typename Items::value_type > > collect_pages(Fetch &&fetch, Items Response::*items, std::size_t max_pages=std::numeric_limits< std::size_t >::max())
Follows cursors through a list operation and collects every page's items.
Definition pagination.hpp:32
std::expected< T, Error > Result
Result type for SDK operations.
Definition error.hpp:50
@ ParseError
The response was not the JSON the API documents.
Definition error.hpp:23