Repository navigation
Expand file tree
/
Copy pathhacker_news.cpp
More file actions
45 lines (39 loc) · 1.45 KB
/
Copy pathhacker_news.cpp
File metadata and controls
45 lines (39 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "../polyweb.hpp"
#include <assert.h>
#include <iostream>
#include <memory>
#include <nlohmann/json.hpp>
#include <stddef.h>
#include <stdlib.h>
#include <vector>
using nlohmann::json;
int main() {
(void) pn::init();
pw::Response resp;
if (pn::Status result = pw::fetch("https://hacker-news.firebaseio.com/v0/topstories.json", resp); !result) {
std::cerr << "Error: " << result.error().message() << std::endl;
return 1;
}
assert(resp.status_code == 200);
json story_ids = json::parse(resp.body_string());
assert(story_ids.is_array() && story_ids.size() >= 10);
std::cout << "10 stories on Hacker News today:" << std::endl;
std::vector<std::shared_ptr<tp::Task>> tasks;
for (size_t i = 0; i < 10; ++i) {
tasks.push_back(pw::threadpool.schedule([&story_ids, i]() {
pw::Response resp;
if (pn::Status result = pw::fetch("https://hacker-news.firebaseio.com/v0/item/" + std::to_string(story_ids[i].get<int>()) + ".json", resp); !result) {
std::cerr << "Error: " << result.error().message() << std::endl;
exit(1);
}
assert(resp.status_code == 200);
json story = json::parse(resp.body_string());
std::cout << story["title"].get<std::string>() << std::endl;
}));
}
for (const auto& task : tasks) {
assert(task->wait() == tp::TASK_STATUS_SUCCESS);
}
(void) pn::quit();
return 0;
}