kalshi-cpp 0.8.0
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 <iterator>
7#include <limits>
8#include <optional>
9#include <string>
10#include <string_view>
11#include <unordered_set>
12#include <utility>
13#include <vector>
14
15namespace kalshi {
16
17namespace detail {
18
19inline std::string take_page_cursor(std::string& cursor) {
20 return std::move(cursor);
21}
22
23inline std::string take_page_cursor(std::optional<std::string>& cursor) {
24 return std::move(cursor).value_or("");
25}
26
27} // namespace detail
28
44template <class Fetch, class Response, class Items>
45[[nodiscard]] Result<std::vector<typename Items::value_type>>
46collect_pages(Fetch&& fetch, Items Response::*items,
47 std::size_t max_pages = (std::numeric_limits<std::size_t>::max)()) {
48 std::vector<typename Items::value_type> all;
49 std::string cursor;
50 std::unordered_set<std::string> seen;
51 for (std::size_t page = 0; page < max_pages; ++page) {
52 Result<Response> response = fetch(std::string_view{cursor});
53 if (!response) {
54 return std::unexpected(std::move(response.error()));
55 }
56 Items& batch = (*response).*items;
57 all.insert(all.end(), std::make_move_iterator(batch.begin()),
58 std::make_move_iterator(batch.end()));
59 std::string next;
60 if constexpr (requires { response->cursor; }) {
61 next = detail::take_page_cursor(response->cursor);
62 } else {
63 next = detail::take_page_cursor(response->next_cursor);
64 }
65 if (next.empty()) {
66 break;
67 }
68 if (!seen.insert(next).second) {
69 return std::unexpected(
70 Error{ErrorCode::ParseError, "Pagination cursor repeated: " + next, 0, {}});
71 }
72 cursor = std::move(next);
73 }
74 return all;
75}
76
77} // namespace kalshi
std::string take_page_cursor(std::string &cursor)
Definition pagination.hpp:19
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:46
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