64 lines
1.5 KiB
C++
64 lines
1.5 KiB
C++
#pragma once
|
|
|
|
#include <string>
|
|
#include <thread>
|
|
|
|
#include "httplib.h"
|
|
#include "rapidjson/document.h"
|
|
|
|
inline httplib::SSLClient* cli = nullptr;
|
|
inline httplib::Headers headers;
|
|
|
|
template<typename T>
|
|
bool json_to_obj(const std::string& json, std::vector<T>& out) {
|
|
if (json.empty())
|
|
return false;
|
|
rapidjson::Document d;
|
|
d.Parse(json.c_str());
|
|
|
|
const auto& obj_array = d.GetArray();
|
|
for (const auto& obj: obj_array) {
|
|
out.push_back(T::from_json(obj));
|
|
}
|
|
return !out.empty();
|
|
}
|
|
|
|
template<typename T>
|
|
bool json_to_obj(const std::string& json, T& out) {
|
|
std::vector<T> vec;
|
|
const bool ok = json_to_obj<T>(json, vec);
|
|
if (ok) {
|
|
out = vec[0];
|
|
}
|
|
return ok;
|
|
}
|
|
|
|
inline std::string post_request(const std::string& api, const httplib::Params& params) {
|
|
if (!cli)
|
|
return "";
|
|
auto res = cli->Post("/rpc/" + api + ".asp", headers, params);
|
|
if (!res || res->status != 200)
|
|
return "";
|
|
return parser_js(res->body);
|
|
}
|
|
|
|
inline std::string get_request(const std::string& api) {
|
|
if (!cli)
|
|
return "";
|
|
auto res = cli->Get("/rpc/" + api + ".asp", headers);
|
|
if (!res || res->status != 200)
|
|
return "";
|
|
return parser_js(res->body);
|
|
}
|
|
|
|
template<typename T>
|
|
bool post_request(const std::string& api, const httplib::Params& params, T& out) {
|
|
return json_to_obj(post_request(api, params), out);
|
|
}
|
|
|
|
template<typename T>
|
|
bool get_request(const std::string& api, T& out) {
|
|
return json_to_obj(get_request(api), out);
|
|
}
|
|
|