Basic JSON RESTful client fetching items from a local server at application start and adding them to the model.
This commit is contained in:
60
network/servercommunicator.cpp
Normal file
60
network/servercommunicator.cpp
Normal file
@ -0,0 +1,60 @@
|
||||
#include "servercommunicator.h"
|
||||
#include "apiroutes.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QRestReply>
|
||||
|
||||
using namespace Qt::StringLiterals;
|
||||
|
||||
ServerCommunicator::ServerCommunicator(QObject* parent)
|
||||
: QObject{parent} {
|
||||
m_netManager.setAutoDeleteReplies(true);
|
||||
m_restManager = std::make_shared<QRestAccessManager>(&m_netManager);
|
||||
m_serviceApi = std::make_shared<QNetworkRequestFactory>();
|
||||
setUrl(baseUrl);
|
||||
}
|
||||
|
||||
bool ServerCommunicator::sslSupported() {
|
||||
#if QT_CONFIG(ssl)
|
||||
return QSslSocket::supportsSsl();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
QUrl ServerCommunicator::url() const { return m_serviceApi->baseUrl(); }
|
||||
|
||||
void ServerCommunicator::setUrl(const QUrl& url) {
|
||||
if (m_serviceApi->baseUrl() == url) {
|
||||
return;
|
||||
}
|
||||
m_serviceApi->setBaseUrl(url);
|
||||
QHttpHeaders authenticationHeaders;
|
||||
m_serviceApi->setCommonHeaders(authenticationHeaders);
|
||||
emit urlChanged();
|
||||
}
|
||||
|
||||
void ServerCommunicator::fetchItems() {
|
||||
/// Set up a GET request
|
||||
m_restManager->get(m_serviceApi->createRequest(ROUTE_ITEMS), this, [this](QRestReply& reply) {
|
||||
if (reply.isSuccess()) {
|
||||
qInfo() << "Fetching items successful.";
|
||||
const QJsonDocument doc = reply.readJson().value();
|
||||
emit itemsFetched(doc.toJson());
|
||||
|
||||
} else {
|
||||
if (reply.hasError()) {
|
||||
const QString errorString = reply.errorString();
|
||||
qCritical() << "ERROR:" << errorString;
|
||||
emit itemsFetchFailure(errorString);
|
||||
} else {
|
||||
int statusCode = reply.httpStatus();
|
||||
qCritical() << "ERROR:" << statusCode;
|
||||
emit itemsFetchFailure(QString::number(statusCode));
|
||||
emit itemsFetchFailure(QString("HTTP status code: %1").arg(statusCode));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user