* @brief Build pagination links from request and query result. * * @param req The original request. * @param limit The pagination limit. * @param offset The current offset. * @param totalCount Total number of items. * @param returnedCount Number of items returned in this response. * @return JSON object with "prev" and "next" links (if applicable). */
| 146 | * @return JSON object with "prev" and "next" links (if applicable). |
| 147 | */ |
| 148 | nlohmann::json BuildPaginationLinks( |
| 149 | const httplib::Request& req, |
| 150 | int limit, |
| 151 | int offset, |
| 152 | int totalCount, |
| 153 | int returnedCount) |
| 154 | { |
| 155 | nlohmann::json links = nlohmann::json::object(); |
| 156 | |
| 157 | // Build base URL from request path |
| 158 | std::string basePath = req.path; |
| 159 | |
| 160 | // Collect query parameters, excluding offset (we'll set it ourselves) |
| 161 | std::vector<std::pair<std::string, std::string>> preservedParams; |
| 162 | for (const auto& param : req.params) |
| 163 | { |
| 164 | if (param.first != "offset") |
| 165 | { |
| 166 | preservedParams.push_back(param); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // Build query string helper |
| 171 | auto buildUrl = [&basePath, &preservedParams](int newOffset) -> std::string { |
| 172 | std::ostringstream url; |
| 173 | url << basePath << "?"; |
| 174 | |
| 175 | bool first = true; |
| 176 | for (const auto& param : preservedParams) |
| 177 | { |
| 178 | if (!first) url << "&"; |
| 179 | url << param.first << "=" << param.second; |
| 180 | first = false; |
| 181 | } |
| 182 | |
| 183 | if (!first) url << "&"; |
| 184 | url << "offset=" << newOffset; |
| 185 | |
| 186 | return url.str(); |
| 187 | }; |
| 188 | |
| 189 | // Previous page link (only if not at the beginning) |
| 190 | if (offset > 0) |
| 191 | { |
| 192 | int prevOffset = std::max(0, offset - limit); |
| 193 | links["prev"] = buildUrl(prevOffset); |
| 194 | } |
| 195 | |
| 196 | // Next page link (only if there are more items) |
| 197 | if (offset + returnedCount < totalCount) |
| 198 | { |
| 199 | int nextOffset = offset + limit; |
| 200 | links["next"] = buildUrl(nextOffset); |
| 201 | } |
| 202 | |
| 203 | return links; |
| 204 | } |
| 205 |
no outgoing calls
no test coverage detected