magpie/API/requests/request.h

70 lines
1.8 KiB
C
Raw Normal View History

2024-01-20 21:17:21 +00:00
// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <memory>
#include <optional>
#include <QObject>
#include <QString>
#include <QVariantMap>
#include <QNetworkReply>
namespace Request {
class Request : public QObject {
Q_OBJECT
public:
Request (const QUrl& url);
virtual ~Request ();
void send (QNetworkAccessManager& manager);
void cancel ();
void setAuthorizationToken(const QString& token);
signals:
void done ();
void success (const QVariantMap& data);
void error (const QString& error, const std::optional<QVariantMap>& data);
protected:
virtual void aquireRequest (QNetworkAccessManager& manager);
virtual void initializeRequest ();
virtual void onSuccess (const QVariantMap& data);
virtual void onError (const QString& error, const std::optional<QVariantMap>& data);
std::optional<QString> validate ();
std::optional<QVariantMap> readResult ();
static bool validateResponse (const std::optional<QVariantMap>& data, const std::map<QString, QMetaType::Type>& structure);
static QUrl createUrl(QUrl base, const QString& path);
bool stateTerminal() const;
constexpr static const char * const json = "application/json";
constexpr static const char * const urlEncoded = "application/x-www-form-urlencoded";
private slots:
void onFinished ();
protected:
static const std::map<QString, QMetaType::Type> resultStructure;
enum class State {
initial,
sent,
responded,
cancelled
};
struct NetworkReplyDeleter {
void operator () (QNetworkReply* reply) {
reply->deleteLater();
}
};
State state;
QNetworkRequest request;
std::unique_ptr<QNetworkReply, NetworkReplyDeleter> reply;
bool emptyResult;
};
}