86 lines
2.4 KiB
C++
86 lines
2.4 KiB
C++
// ApiClient.h
|
||
#ifndef APICLIENT_H
|
||
#define APICLIENT_H
|
||
|
||
#include <QObject>
|
||
#include <QString>
|
||
#include <QJsonObject>
|
||
#include <functional>
|
||
#include "HttpClient.h"
|
||
|
||
class UserInfo{
|
||
public:
|
||
QString userId;
|
||
QString userName;
|
||
QString role;
|
||
};
|
||
|
||
|
||
class ApiClient : public QObject
|
||
{
|
||
Q_OBJECT
|
||
public:
|
||
explicit ApiClient(QObject *parent = nullptr);
|
||
~ApiClient();
|
||
|
||
static ApiClient* getInstance();
|
||
|
||
AeaQt::HttpClient* httpClient() const;
|
||
|
||
void setBaseUrl(const QString &baseUrl);
|
||
QString baseUrl() const;
|
||
|
||
void setToken(const QString &token);
|
||
QString token() const;
|
||
|
||
using SuccessCB = std::function<void(const QJsonObject &data)>; // 返回的 data 字段
|
||
using FailedCB = std::function<void(const QString &error)>;
|
||
using BinarySuccessCB = std::function<void(const QByteArray &data)>; // 二进制原始数据回调
|
||
|
||
void login(const QString &username, const QString &password, SuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
// 设置和获取用户信息接口
|
||
void setUserInfo(const UserInfo &userInfo){
|
||
m_userInfo = userInfo;
|
||
};
|
||
void setUserInfo(QString userId, QString userName, QString role) {
|
||
m_userInfo.userId = userId;
|
||
m_userInfo.userName = userName;
|
||
m_userInfo.role = role;
|
||
};
|
||
UserInfo userInfo() const{
|
||
return m_userInfo;
|
||
};
|
||
QString getUsername() const
|
||
{
|
||
return userInfo().userName;
|
||
// return qgetenv("USERNAME"); // Windows
|
||
// return qgetenv("USER"); // Linux/Mac
|
||
}
|
||
QString getRole()
|
||
{
|
||
return m_userInfo.role;
|
||
}
|
||
|
||
void get(const QString &path, SuccessCB onSuccess, FailedCB onFailed);
|
||
void post(const QString &path, const QJsonObject &body, SuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
void put(const QString &path, const QJsonObject &body, SuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
void del(const QString &path, SuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
// 获取二进制原始数据(不走 JSON 解析,直接返回 QByteArray)
|
||
void getBinary(const QString &path, BinarySuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
private:
|
||
void handleResponse(const QJsonObject &resp, SuccessCB onSuccess, FailedCB onFailed);
|
||
|
||
private:
|
||
static ApiClient* m_instance;
|
||
AeaQt::HttpClient *m_httpClient;
|
||
QString m_token; // 保存的 Bearer token(带前缀)
|
||
QString m_baseUrl;
|
||
UserInfo m_userInfo;
|
||
};
|
||
|
||
#endif // APICLIENT_H
|