Move all RPC to connection class

This commit is contained in:
Aditya Kulkarni
2018-11-01 14:34:44 -07:00
parent 1b4ced8c82
commit 68aeca7f09
5 changed files with 112 additions and 208 deletions

View File

@@ -1,12 +1,12 @@
#ifndef CONNECTION_H
#define CONNECTION_H
#include "mainwindow.h"
#include "ui_connection.h"
#include "precompiled.h"
using json = nlohmann::json;
class MainWindow;
class RPC;
enum ConnectionType {
@@ -59,17 +59,67 @@ private:
*/
class Connection {
public:
Connection(QNetworkAccessManager* c, QNetworkRequest* r, std::shared_ptr<ConnectionConfig> conf);
Connection(MainWindow* m, QNetworkAccessManager* c, QNetworkRequest* r, std::shared_ptr<ConnectionConfig> conf);
~Connection();
QNetworkAccessManager* restclient;
QNetworkRequest* request;
std::shared_ptr<ConnectionConfig> config;
MainWindow* main;
void doRPC(const json& payload, const std::function<void(json)>& cb,
const std::function<void(QNetworkReply::NetworkError, const json&)>& ne);
const std::function<void(QNetworkReply*, const json&)>& ne);
void doRPCWithDefaultErrorHandling(const json& payload, const std::function<void(json)>& cb);
void doRPCIgnoreError(const json& payload, const std::function<void(json)>& cb) ;
void showTxError(const QString& error);
// Batch method. Note: Because of the template, it has to be in the header file.
template<class T>
void doBatchRPC(const QList<T>& payloads,
std::function<json(T)> payloadGenerator,
std::function<void(QMap<T, json>*)> cb) {
auto responses = new QMap<T, json>(); // zAddr -> list of responses for each call.
int totalSize = payloads.size();
for (auto item: payloads) {
json payload = payloadGenerator(item);
QNetworkReply *reply = restclient->post(*request, QByteArray::fromStdString(payload.dump()));
QObject::connect(reply, &QNetworkReply::finished, [=] {
reply->deleteLater();
auto all = reply->readAll();
auto parsed = json::parse(all.toStdString(), nullptr, false);
if (reply->error() != QNetworkReply::NoError) {
qDebug() << QString::fromStdString(parsed.dump());
qDebug() << reply->errorString();
(*responses)[item] = json::object(); // Empty object
} else {
if (parsed.is_discarded()) {
(*responses)[item] = json::object(); // Empty object
} else {
(*responses)[item] = parsed["result"];
}
}
});
}
auto waitTimer = new QTimer(main);
QObject::connect(waitTimer, &QTimer::timeout, [=]() {
if (responses->size() == totalSize) {
waitTimer->stop();
cb(responses);
waitTimer->deleteLater();
}
});
waitTimer->start(100);
}
};
#endif