1#include <IRestApi.h>
2
3#include <QNetworkAccessManager>
4#include <QNetworkReply>
5#include <QJsonDocument>
6#include <QJsonObject>
7#include <QJsonArray>
8
9#include <QLogger.h>
10
11using namespace QLogger;
12using namespace GitServer;
13
14IRestApi::IRestApi(const ServerAuthentication &auth, QObject *parent)
15 : QObject(parent)
16 , mManager(new QNetworkAccessManager())
17 , mAuth(auth)
18{
19}
20
21IRestApi::~IRestApi()
22{
23 delete mManager;
24}
25
26QJsonDocument IRestApi::validateData(QNetworkReply *reply, QString &errorString)
27{
28 const auto data = reply->readAll();
29 const auto jsonDoc = QJsonDocument::fromJson(data);
30
31 if (reply->error() != QNetworkReply::NoError)
32 {
33 QLog_Error("Ui", QString("Error #%1 - %2.").arg(QString::number(reply->error()), reply->errorString()));
34
35 errorString = reply->errorString();
36
37 return QJsonDocument();
38 }
39
40 if (jsonDoc.isNull())
41 {
42 QLog_Error("Ui", QString("Error when parsing Json. Current data:\n%1").arg(QString::fromUtf8(data)));
43 return QJsonDocument();
44 }
45
46 const auto jsonObject = jsonDoc.object();
47 if (jsonObject.contains(QStringLiteral("message")))
48 {
49 const auto message = jsonObject[QStringLiteral("message")].toString();
50 QString details;
51
52 if (jsonObject.contains(QStringLiteral("errors")))
53 {
54 const auto errors = jsonObject[QStringLiteral("errors")].toArray();
55
56 for (const auto &error : errors)
57 details = error[QStringLiteral("message")].toString();
58
59 errorString = message + ". " + details;
60
61 QLog_Error("Ui", errorString);
62
63 return QJsonDocument();
64 }
65 }
66 else if (jsonObject.contains(QStringLiteral("error")))
67 {
68 errorString = jsonObject[QStringLiteral("error")].toString();
69
70 QLog_Error("Ui", errorString);
71
72 return QJsonDocument();
73 }
74
75 reply->deleteLater();
76
77 return jsonDoc;
78}
79