magpie/API/api.h

65 lines
2.2 KiB
C++

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <memory>
#include <optional>
#include <map>
#include <functional>
#include <QObject>
#include <QString>
#include <QUrl>
#include <QJSValue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include "models/magpie.h"
#include "requests/request.h"
class API : public QObject {
Q_OBJECT
public:
using SuccessMapHandler = std::function<void(const QVariantMap&)>;
using SuccessListHandler = std::function<void(const QVariantList&)>;
using ErrorHandler = std::function<void(const QString&, const std::optional<QVariantMap>&)>;
using RequestId = unsigned int;
explicit API(Models::Magpie& magpie, QObject* parent = nullptr);
RequestId requestAssets(const SuccessListHandler& success, const ErrorHandler& error);
RequestId requestCurrencies(const SuccessListHandler& success, const ErrorHandler& error);
RequestId poll(const SuccessMapHandler& success, const ErrorHandler& error, bool clear = false);
static const RequestId none = 0;
public slots:
void cancelRequest(RequestId id);
RequestId test(const QString& path, const QJSValue& finished = QJSValue());
RequestId sendRegister(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
RequestId sendLogin(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
RequestId addAsset(
const QString& title,
const QString& icon,
const QColor& color,
Models::Currency::ID currency,
const QJSValue& finished = QJSValue()
);
RequestId deleteAsset(unsigned int id, const QJSValue& finished = QJSValue());
private slots:
void onRequestDone(RequestId id);
private:
void callCallback(const QJSValue& callback, const QString& error = QString(), const QJSValueList& arguments = QJSValueList()) const;
RequestId registerAndSend(std::unique_ptr<Request::Request> request);
private:
RequestId idCounter;
Models::Magpie& magpie;
QNetworkAccessManager network;
std::map<RequestId, std::unique_ptr<Request::Request>> requests;
};