feat(registry): paginate package search results
This commit is contained in:
1 parent
41a74bc925
commit
7bd04718df
6 files changed
+73
-8
No files matched your search
@@ -15,6 +15,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <sys/random.h>
|
||||
@@ -797,13 +798,47 @@ HttpResponse RegistryService::handle_request(const HttpRequest &req) {
|
||||
}
|
||||
visible.push_back(&p);
|
||||
}
|
||||
|
||||
std::size_t limit = 100;
|
||||
std::size_t offset = 0;
|
||||
const auto parse_size = [](const std::string &text, std::size_t max, std::size_t &out) {
|
||||
std::size_t value = 0;
|
||||
const auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
|
||||
if (ec != std::errc{} || ptr != text.data() + text.size() || value > max) {
|
||||
return false;
|
||||
}
|
||||
out = value;
|
||||
return true;
|
||||
};
|
||||
if (const auto it = req.query.find("limit");
|
||||
it != req.query.end() && !parse_size(it->second, 500, limit)) {
|
||||
return HttpResponse::error_json(400, "invalid_limit",
|
||||
"limit must be an integer in [0, 500]");
|
||||
}
|
||||
if (const auto it = req.query.find("offset");
|
||||
it != req.query.end() && !parse_size(it->second, 1000000, offset)) {
|
||||
return HttpResponse::error_json(400, "invalid_offset",
|
||||
"offset must be a non-negative integer");
|
||||
}
|
||||
|
||||
const std::size_t total = visible.size();
|
||||
std::vector<const PackageMeta *> page;
|
||||
for (std::size_t i = offset; i < total && page.size() < limit; ++i) {
|
||||
page.push_back(visible[i]);
|
||||
}
|
||||
return HttpResponse::json(
|
||||
200, "{\"packages\":" + json_array(visible, [](const PackageMeta *p) {
|
||||
return "{\"name\":" + json_quote(p->name) +
|
||||
",\"description\":" + json_quote(p->description) +
|
||||
",\"is_private\":" + std::string{p->is_private ? "true" : "false"} +
|
||||
",\"release_count\":" + std::to_string(p->releases.size()) + '}';
|
||||
}) + "}\n");
|
||||
200, "{\"packages\":" +
|
||||
json_array(page,
|
||||
[](const PackageMeta *p) {
|
||||
return "{\"name\":" + json_quote(p->name) +
|
||||
",\"description\":" + json_quote(p->description) +
|
||||
",\"is_private\":" +
|
||||
std::string{p->is_private ? "true" : "false"} +
|
||||
",\"release_count\":" +
|
||||
std::to_string(p->releases.size()) + '}';
|
||||
}) +
|
||||
",\"total\":" + std::to_string(total) + ",\"limit\":" + std::to_string(limit) +
|
||||
",\"offset\":" + std::to_string(offset) + "}\n");
|
||||
}
|
||||
|
||||
// /api/v1/packages/<name>[/<version>[/download|/yank]]
|
||||
|
||||
Reference in new issue
Block a user