mirror of
https://github.com/allankoechke/pocketbase-cpp.git
synced 2026-12-05 01:16:10 +00:00
Project refactor
This commit is contained in:
@@ -19,7 +19,7 @@ add_executable(pocketbase-cpp
|
||||
sdk/adminservice.h sdk/adminservice.cpp
|
||||
sdk/collectionservice.h sdk/collectionservice.cpp
|
||||
sdk/fileservice.h sdk/fileservice.cpp
|
||||
sdk/realtimeservice.h sdk/realtimeservice.cpp
|
||||
# sdk/realtimeservice.h sdk/realtimeservice.cpp
|
||||
sdk/settingsservice.h sdk/settingsservice.cpp
|
||||
sdk/logservice.h sdk/logservice.cpp
|
||||
sdk/healthservice.h sdk/healthservice.cpp
|
||||
@@ -38,6 +38,10 @@ add_executable(pocketbase-cpp
|
||||
sdk/models/backupmodel.hpp
|
||||
sdk/models/collectionmodel.hpp
|
||||
sdk/models/fileuploadmodel.hpp
|
||||
# sdk/utils/eventloop.h sdk/utils/eventloop.cpp
|
||||
sdk/event.h sdk/event.cpp
|
||||
sdk/models/recordmodel.hpp
|
||||
sdk/utils/utils.h
|
||||
)
|
||||
target_link_libraries(pocketbase-cpp Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Network)
|
||||
|
||||
|
||||
3
main.cpp
3
main.cpp
@@ -1,8 +1,11 @@
|
||||
#include <QCoreApplication>
|
||||
#include "sdk/qpocketbase.h"
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
QCoreApplication a(argc, argv);
|
||||
|
||||
QPocketBase client;
|
||||
|
||||
return a.exec();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#include "adminservice.h"
|
||||
#include "AdminService.h"
|
||||
|
||||
AdminAuthResponse::AdminAuthResponse(const QString& token, std::shared_ptr<AdminModel> admin)
|
||||
: token(token), admin(admin) {}
|
||||
@@ -26,10 +25,10 @@ QString AdminService::baseCrudPath() const {
|
||||
std::shared_ptr<BaseModel> AdminService::update(const QString& id, const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
auto item = CrudService::update(id, bodyParams, queryParams);
|
||||
try {
|
||||
if (client->getAuthStore()->getModel()->getCollectionId().isNull() &&
|
||||
item->getId() == client->getAuthStore()->getModel()->getId()) {
|
||||
client->getAuthStore()->save(client->getAuthStore()->getToken(), item);
|
||||
}
|
||||
// if (client->authStore()->model()->getCollectionId().isNull() &&
|
||||
// item->getId() == client->authStore()->getModel()->getId()) {
|
||||
// client->authStore()->save(client->authStore()->getToken(), item);
|
||||
// }
|
||||
} catch (...) {
|
||||
// Handle exceptions
|
||||
}
|
||||
@@ -37,12 +36,12 @@ std::shared_ptr<BaseModel> AdminService::update(const QString& id, const QJsonOb
|
||||
}
|
||||
|
||||
bool AdminService::deleteItem(const QString& id, const QJsonObject& queryParams) {
|
||||
auto item = CrudService::deleteItem(id, queryParams);
|
||||
auto item = CrudService::deleteOne(id, queryParams);
|
||||
try {
|
||||
if (client->getAuthStore()->getModel()->getCollectionId().isNull() &&
|
||||
item->getId() == client->getAuthStore()->getModel()->getId()) {
|
||||
client->getAuthStore()->clear();
|
||||
}
|
||||
// if (client->authStore()->getModel()->getCollectionId().isNull() &&
|
||||
// item->getId() == client->authStore()->getModel()->getId()) {
|
||||
// client->authStore()->clear();
|
||||
// }
|
||||
} catch (...) {
|
||||
// Handle exceptions
|
||||
}
|
||||
@@ -50,32 +49,37 @@ bool AdminService::deleteItem(const QString& id, const QJsonObject& queryParams)
|
||||
}
|
||||
|
||||
AdminAuthResponse AdminService::authResponse(const QJsonObject& responseData) {
|
||||
QJsonObject adminData = responseData.value("admin").toObject();
|
||||
QString token = responseData.value("token").toString();
|
||||
auto admin = decode(adminData);
|
||||
if (!token.isEmpty() && admin) {
|
||||
client->getAuthStore()->save(token, admin);
|
||||
}
|
||||
return AdminAuthResponse(token, admin);
|
||||
// QJsonObject adminData = responseData.value("admin").toObject();
|
||||
// QString token = responseData.value("token").toString();
|
||||
// auto admin = decode(adminData);
|
||||
// if (!token.isEmpty() && admin) {
|
||||
// client->authStore()->save(token, admin);
|
||||
// }
|
||||
// return AdminAuthResponse(token, admin);
|
||||
return AdminAuthResponse{"", nullptr};
|
||||
}
|
||||
|
||||
AdminAuthResponse AdminService::authWithPassword(const QString& email, const QString& password, const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("identity", email);
|
||||
params.insert("password", password);
|
||||
QJsonObject responseData = client->send(baseCrudPath() + "/auth-with-password", { {"method", "POST"}, {"params", queryParams}, {"body", params}, {"headers", QJsonObject{{"Authorization", ""}}} });
|
||||
return authResponse(responseData);
|
||||
auto reply = client->send(baseCrudPath() + "/auth-with-password", { {"method", "POST"}, {"params", queryParams}, {"body", params}, {"headers", QJsonObject{{"Authorization", ""}}} });
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [&](){
|
||||
// QJsonObject responseData
|
||||
});
|
||||
// return authResponse(responseData);
|
||||
}
|
||||
|
||||
AdminAuthResponse AdminService::authRefresh(const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
QJsonObject responseData = client->send(baseCrudPath() + "/auth-refresh", { {"method", "POST"}, {"params", queryParams}, {"body", bodyParams} });
|
||||
return authResponse(responseData);
|
||||
// QJsonObject responseData = client->send(baseCrudPath() + "/auth-refresh", { {"method", "POST"}, {"params", queryParams}, {"body", bodyParams} });
|
||||
return authResponse(QJsonObject{});
|
||||
}
|
||||
|
||||
bool AdminService::requestPasswordReset(const QString& email, const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("email", email);
|
||||
client->send(baseCrudPath() + "/request-password-reset", { {"method", "POST"}, {"params", queryParams}, {"body", params} });
|
||||
// client->send(baseCrudPath() + "/request-password-reset", { {"method", "POST"}, {"params", queryParams}, {"body", params} });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -84,6 +88,6 @@ bool AdminService::confirmPasswordReset(const QString& passwordResetToken, const
|
||||
params.insert("token", passwordResetToken);
|
||||
params.insert("password", password);
|
||||
params.insert("passwordConfirm", passwordConfirm);
|
||||
client->send(baseCrudPath() + "/confirm-password-reset", { {"method", "POST"}, {"params", queryParams}, {"body", params} });
|
||||
// client->send(baseCrudPath() + "/confirm-password-reset", { {"method", "POST"}, {"params", queryParams}, {"body", params} });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -7,8 +7,11 @@
|
||||
#include <QString>
|
||||
#include <QJsonObject>
|
||||
|
||||
#include "qpocketbase.h"
|
||||
#include "utils/crudservice.h"
|
||||
#include "models/AdminModel.h"
|
||||
#include "baseauthstore.h"
|
||||
#include "recordservice.h"
|
||||
|
||||
class AdminAuthResponse {
|
||||
public:
|
||||
|
||||
@@ -20,6 +20,10 @@ public:
|
||||
void save(const QString& token = "", std::shared_ptr<RecordService> model = nullptr);
|
||||
void clear();
|
||||
|
||||
// TODO
|
||||
QString getCollectionId() const { return ""; }
|
||||
QString getCollectionName() const { return ""; }
|
||||
|
||||
signals:
|
||||
|
||||
private:
|
||||
|
||||
36
sdk/event.cpp
Normal file
36
sdk/event.cpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#include "event.h"
|
||||
|
||||
Event::Event(const QString& id, const QString& event, const QString& data, int retry)
|
||||
: id(id), event(event), data(data), retry(retry) {}
|
||||
|
||||
QString Event::getId() const {
|
||||
return id;
|
||||
}
|
||||
|
||||
QString Event::getEvent() const {
|
||||
return event;
|
||||
}
|
||||
|
||||
QString Event::getData() const {
|
||||
return data;
|
||||
}
|
||||
|
||||
int Event::getRetry() const {
|
||||
return retry;
|
||||
}
|
||||
|
||||
void Event::setId(const QString& id) {
|
||||
this->id = id;
|
||||
}
|
||||
|
||||
void Event::setEvent(const QString& event) {
|
||||
this->event = event;
|
||||
}
|
||||
|
||||
void Event::setData(const QString& data) {
|
||||
this->data = data;
|
||||
}
|
||||
|
||||
void Event::setRetry(int retry) {
|
||||
this->retry = retry;
|
||||
}
|
||||
27
sdk/event.h
Normal file
27
sdk/event.h
Normal file
@@ -0,0 +1,27 @@
|
||||
#ifndef EVENT_H
|
||||
#define EVENT_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
class Event {
|
||||
public:
|
||||
Event(const QString& id = "", const QString& event = "message", const QString& data = "", int retry = -1);
|
||||
|
||||
QString getId() const;
|
||||
QString getEvent() const;
|
||||
QString getData() const;
|
||||
int getRetry() const;
|
||||
|
||||
void setId(const QString& id);
|
||||
void setEvent(const QString& event);
|
||||
void setData(const QString& data);
|
||||
void setRetry(int retry);
|
||||
|
||||
private:
|
||||
QString id;
|
||||
QString event;
|
||||
QString data;
|
||||
int retry;
|
||||
};
|
||||
|
||||
#endif // EVENT_H
|
||||
54
sdk/models/recordmodel.hpp
Normal file
54
sdk/models/recordmodel.hpp
Normal file
@@ -0,0 +1,54 @@
|
||||
#ifndef RECORDModelMODEL_HPP
|
||||
#define RECORDModelMODEL_HPP
|
||||
|
||||
#include <QString>
|
||||
#include <QMap>
|
||||
#include <QVariant>
|
||||
#include "utils/basemodel.h"
|
||||
#include "../utils/utils.h"
|
||||
|
||||
class RecordModel : public BaseModel {
|
||||
public:
|
||||
QString collectionId;
|
||||
QString collectionName;
|
||||
QMap<QString, QVariant> expand;
|
||||
|
||||
RecordModel(const QJsonObject &data) {
|
||||
qDebug() << "[Data Record Model] " << data;
|
||||
load(data);
|
||||
}
|
||||
|
||||
void load(const QJsonObject &data) override {
|
||||
BaseModel::load(data);
|
||||
expand.clear();
|
||||
|
||||
for (auto it = data.begin(); it != data.end(); ++it) {
|
||||
QString key = Utils::camelToSnake(it.key()).replace("@", "");
|
||||
expand.insert(key, QVariant(it.value()));
|
||||
this->setProperty(key.toStdString().c_str(), QVariant(it.value()));
|
||||
}
|
||||
|
||||
loadExpanded();
|
||||
}
|
||||
|
||||
static QList<RecordModel> parseExpanded(const QVariant &data) {
|
||||
QList<RecordModel> recordModels;
|
||||
if (data.type() == QVariant::List) {
|
||||
for (const auto &item : data.toList()) {
|
||||
recordModels.append(RecordModel(item.toJsonObject()));
|
||||
}
|
||||
} else if (data.type() == QVariant::Map) {
|
||||
recordModels.append(RecordModel(data.toJsonObject()));
|
||||
}
|
||||
return recordModels;
|
||||
}
|
||||
|
||||
void loadExpanded() {
|
||||
for (auto it = expand.begin(); it != expand.end(); ++it) {
|
||||
auto l = parseExpanded(it.value());
|
||||
expand[it.key()] = QVariantList(l.begin(), l.end());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#endif // RECORDModelMODEL_HPP
|
||||
@@ -12,16 +12,23 @@ class BaseModel : public QObject {
|
||||
public:
|
||||
explicit BaseModel(const QJsonObject& data = QJsonObject(), QObject* parent = nullptr);
|
||||
|
||||
QString toString() const;
|
||||
QString repr() const;
|
||||
void load(const QJsonObject& data);
|
||||
bool isNew() const;
|
||||
BaseModel(const BaseModel &data) {
|
||||
id = data.getId();
|
||||
created = data.getCreated();
|
||||
updated = data.getUpdated();
|
||||
}
|
||||
|
||||
QString getId() const;
|
||||
QDateTime getCreated() const;
|
||||
QDateTime getUpdated() const;
|
||||
|
||||
private:
|
||||
virtual QString toString() const;
|
||||
virtual QString repr() const;
|
||||
virtual void load(const QJsonObject& data);
|
||||
virtual bool isNew() const;
|
||||
|
||||
virtual QString getId() const;
|
||||
virtual QDateTime getCreated() const;
|
||||
virtual QDateTime getUpdated() const;
|
||||
|
||||
protected:
|
||||
QString id;
|
||||
QDateTime created;
|
||||
QDateTime updated;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include "BackupService.h"
|
||||
#include "CollectionService.h"
|
||||
#include "LogService.h"
|
||||
#include "RealtimeService.h"
|
||||
// #include "RealtimeService.h"
|
||||
#include "RecordService.h"
|
||||
#include "SettingsService.h"
|
||||
#include "RecordService.h"
|
||||
@@ -23,7 +23,7 @@ QPocketBase::QPocketBase(const QString& baseUrl, const QString& lang, std::share
|
||||
m_admins(std::make_shared<AdminService>(this)),
|
||||
m_collections(std::make_shared<CollectionService>(this)),
|
||||
m_files(std::make_shared<FileService>(this)),
|
||||
m_realtime(std::make_shared<RealtimeService>(this)),
|
||||
// m_realtime(std::make_shared<RealtimeService>(this)),
|
||||
m_settings(std::make_shared<SettingsService>(this)),
|
||||
m_logs(std::make_shared<LogService>(this)),
|
||||
m_health(std::make_shared<HealthService>(this)),
|
||||
@@ -94,22 +94,22 @@ QNetworkReply* QPocketBase::send(const QString& path, const QJsonObject& reqConf
|
||||
}
|
||||
|
||||
QUrl QPocketBase::getFileUrl(const RecordService& record, const QString& filename, const QMap<QString, QString>& queryParams) {
|
||||
QStringList parts = { "api", "files", QUrl::toPercentEncoding(record.collectionId()), QUrl::toPercentEncoding(record.id()), QUrl::toPercentEncoding(filename) };
|
||||
QUrl url = buildUrl(parts.join("/"));
|
||||
if (!queryParams.isEmpty()) {
|
||||
QUrlQuery query;
|
||||
for (auto it = queryParams.begin(); it != queryParams.end(); ++it) {
|
||||
query.addQueryItem(it.key(), it.value());
|
||||
}
|
||||
url.setQuery(query);
|
||||
}
|
||||
return url;
|
||||
// QStringList parts = { "api", "files", QUrl::toPercentEncoding(record.collectionId), QUrl::toPercentEncoding(record.getId()), QUrl::toPercentEncoding(filename) };
|
||||
// QUrl url = buildUrl(parts.join("/"));
|
||||
// if (!queryParams.isEmpty()) {
|
||||
// QUrlQuery query;
|
||||
// for (auto it = queryParams.begin(); it != queryParams.end(); ++it) {
|
||||
// query.addQueryItem(it.key(), it.value());
|
||||
// }
|
||||
// url.setQuery(query);
|
||||
// }
|
||||
return QUrl{};
|
||||
}
|
||||
|
||||
QString QPocketBase::getFileToken() {
|
||||
QJsonObject reqConfig;
|
||||
reqConfig["method"] = "POST";
|
||||
QNetworkReply* reply = sendRequest("/api/files/token", reqConfig);
|
||||
QNetworkReply* reply = send("/api/files/token", reqConfig);
|
||||
|
||||
auto data = reply->readAll().data();
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <QDebug>
|
||||
#include <QObject>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
@@ -88,6 +89,11 @@ public:
|
||||
QString lang() const;
|
||||
void setLang(const QString &newLang);
|
||||
|
||||
std::shared_ptr<BaseAuthStore> authStore() { return m_authStore; }
|
||||
|
||||
|
||||
QNetworkReply* send(const QString& path, const QJsonObject& reqConfig);
|
||||
|
||||
signals:
|
||||
|
||||
void baseUrlChanged();
|
||||
@@ -98,7 +104,6 @@ signals:
|
||||
|
||||
private:
|
||||
QUrl buildUrl(const QString& path);
|
||||
QNetworkReply* send(const QString& path, const QJsonObject& reqConfig);
|
||||
|
||||
/// An instance of the local [AuthStore] service.
|
||||
std::shared_ptr<BaseAuthStore> m_authStore;
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
#include "realtimeservice.h"
|
||||
|
||||
RealtimeService::RealtimeService() {}
|
||||
SSEClient::SSEClient(const QString& url, const QString& method, const QMap<QString, QString>& headers, const QByteArray& payload, const QString& encoding, QObject* parent)
|
||||
: QObject(parent) {
|
||||
loopThread = new EventLoop(url, method, headers, payload, encoding, this);
|
||||
connect(loopThread, &EventLoop::finished, loopThread, &QObject::deleteLater);
|
||||
loopThread->start();
|
||||
}
|
||||
|
||||
void SSEClient::addEventListener(const QString& event, std::function<void(const Event&)> callback) {
|
||||
listeners[event] = callback;
|
||||
loopThread->addEventListener(event, callback);
|
||||
}
|
||||
|
||||
void SSEClient::removeEventListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
loopThread->removeEventListener(event);
|
||||
}
|
||||
|
||||
void SSEClient::close() {
|
||||
loopThread->kill = true;
|
||||
loopThread->wait();
|
||||
}
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
#ifndef REALTIMESERVICE_H
|
||||
#define REALTIMESERVICE_H
|
||||
#ifndef SSECLIENT_H
|
||||
#define SSECLIENT_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QMap>
|
||||
#include <functional>
|
||||
#include "EventLoop.h"
|
||||
#include "Event.h"
|
||||
|
||||
class SSEClient : public QObject {
|
||||
Q_OBJECT
|
||||
|
||||
class RealtimeService
|
||||
{
|
||||
public:
|
||||
RealtimeService();
|
||||
explicit SSEClient(const QString& url, const QString& method = "GET", const QMap<QString, QString>& headers = {}, const QByteArray& payload = QByteArray(), const QString& encoding = "utf-8", QObject* parent = nullptr);
|
||||
void addEventListener(const QString& event, std::function<void(const Event&)> callback);
|
||||
void removeEventListener(const QString& event);
|
||||
void close();
|
||||
|
||||
private:
|
||||
EventLoop* loopThread;
|
||||
QMap<QString, std::function<void(const Event&)>> listeners;
|
||||
};
|
||||
|
||||
#endif // REALTIMESERVICE_H
|
||||
#endif // SSECLIENT_H
|
||||
|
||||
@@ -1,5 +1,190 @@
|
||||
#include "recordservice.h"
|
||||
|
||||
RecordService::RecordService(const QString &collectionIdOrName, QObject *parent)
|
||||
: QObject{parent}
|
||||
{}
|
||||
RecordAuthResponse::RecordAuthResponse(const QString &token, const RecordModel &record)
|
||||
: token(token), record(record) {}
|
||||
|
||||
bool RecordAuthResponse::isValid() const {
|
||||
return validateToken(token);
|
||||
}
|
||||
|
||||
bool RecordAuthResponse::validateToken(const QString &token) const {
|
||||
// TODO
|
||||
// Implement token validation logic here
|
||||
return true;
|
||||
}
|
||||
|
||||
AuthProviderInfo::AuthProviderInfo(const QString &name, const QString &state, const QString &codeVerifier, const QString &codeChallenge, const QString &codeChallengeMethod, const QString &authUrl)
|
||||
: name(name), state(state), codeVerifier(codeVerifier), codeChallenge(codeChallenge),
|
||||
codeChallengeMethod(codeChallengeMethod), authUrl(authUrl) {}
|
||||
|
||||
AuthMethodsList::AuthMethodsList(bool usernamePassword, bool emailPassword, const QList<AuthProviderInfo> &authProviders)
|
||||
: usernamePassword(usernamePassword), emailPassword(emailPassword), authProviders(authProviders) {}
|
||||
|
||||
RecordService::RecordService(std::shared_ptr<QPocketBase> client, const QString &collectionIdOrName)
|
||||
: CrudService(client), collectionIdOrName(collectionIdOrName) {}
|
||||
|
||||
std::shared_ptr<BaseModel> RecordService::decode(const QJsonObject &data) {
|
||||
// TODO
|
||||
return std::make_shared<RecordModel>(data);
|
||||
}
|
||||
|
||||
QString RecordService::baseCrudPath() const {
|
||||
return baseCollectionPath() + "/records";
|
||||
}
|
||||
|
||||
QString RecordService::baseCollectionPath() const {
|
||||
return "/api/collections/" + QUrl::toPercentEncoding(collectionIdOrName);
|
||||
}
|
||||
|
||||
QString RecordService::getFileUrl(const RecordModel &record, const QString &filename, const QUrlQuery &queryParams) const {
|
||||
QString baseUrl = client->baseUrl();
|
||||
if (baseUrl.endsWith("/")) {
|
||||
baseUrl.chop(1);
|
||||
}
|
||||
QString result = QString("%1/api/files/%2/%3/%4")
|
||||
.arg(baseUrl, record.collectionId, record.getId(), filename);
|
||||
if (!queryParams.isEmpty()) {
|
||||
result += "?" + queryParams.toString();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void RecordService::subscribe(std::function<void (const QVariant &)> callback) {
|
||||
// client->realtime()->subscribe(collectionIdOrName, callback);
|
||||
}
|
||||
|
||||
void RecordService::subscribeOne(const QString &recordId, std::function<void (const QVariant &)> callback) {
|
||||
// client->realtime()->subscribe(collectionIdOrName + "/" + recordId, callback);
|
||||
}
|
||||
|
||||
void RecordService::unsubscribe(const QStringList &recordIds) {
|
||||
/*if (!recordIds.isEmpty()) {
|
||||
QStringList subs;
|
||||
for (const auto& id : recordIds) {
|
||||
subs.append(collectionIdOrName + "/" + id);
|
||||
}
|
||||
client->realtime()->unsubscribe(subs);
|
||||
} else {
|
||||
client->realtime()->unsubscribeByPrefix(collectionIdOrName);
|
||||
} */
|
||||
}
|
||||
|
||||
RecordModel RecordService::update(const QString &id, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
auto item = CrudService::update(id, bodyParams, Utils::urlQueryToJson(queryParams));
|
||||
try {
|
||||
// if (client->authStore()->model().collectionId != nullptr && item.id() == client->authStore()->model().id()) {
|
||||
// client->authStore()->save(client->authStore()->token(), item);
|
||||
// }
|
||||
} catch (...) {
|
||||
}
|
||||
|
||||
// TODO cast item to RecordModel
|
||||
return RecordModel{QJsonObject{}};
|
||||
}
|
||||
|
||||
bool RecordService::deleteRecord(const QString &id, const QUrlQuery &queryParams) {
|
||||
bool success = CrudService::deleteOne(id, Utils::urlQueryToJson(queryParams));
|
||||
try {
|
||||
// if (success && client->authStore()->model().collectionId() != nullptr && id == client->authStore()->model().id()) {
|
||||
// client->authStore()->clear();
|
||||
// }
|
||||
} catch (...) {
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
RecordAuthResponse RecordService::authResponse(const QJsonObject &responseData) {
|
||||
auto record = std::dynamic_pointer_cast<RecordModel>(decode(responseData["record"].toObject()));
|
||||
QString token = responseData["token"].toString();
|
||||
// if (!token.isEmpty()) { // && !record.isEmpty()) {
|
||||
// client->authStore()->save(token, record);
|
||||
// }
|
||||
// return RecordAuthResponse(token, record);
|
||||
return RecordAuthResponse{"", RecordModel{}};
|
||||
}
|
||||
|
||||
AuthMethodsList RecordService::listAuthMethods(const QUrlQuery &queryParams) {
|
||||
QJsonObject responseData = client->send(baseCollectionPath() + "/auth-methods", "GET", queryParams);
|
||||
bool usernamePassword = responseData["usernamePassword"].toBool();
|
||||
bool emailPassword = responseData["emailPassword"].toBool();
|
||||
QList<AuthProviderInfo> authProviders;
|
||||
for (const auto& provider : responseData["authProviders"].toArray()) {
|
||||
authProviders.append(AuthProviderInfo(
|
||||
provider["name"].toString(),
|
||||
provider["state"].toString(),
|
||||
provider["codeVerifier"].toString(),
|
||||
provider["codeChallenge"].toString(),
|
||||
provider["codeChallengeMethod"].toString(),
|
||||
provider["authUrl"].toString()));
|
||||
}
|
||||
return AuthMethodsList(usernamePassword, emailPassword, authProviders);
|
||||
}
|
||||
|
||||
RecordAuthResponse RecordService::authWithPassword(const QString &usernameOrEmail, const QString &password, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("identity", usernameOrEmail);
|
||||
params.insert("password", password);
|
||||
QJsonObject responseData = client->send(baseCollectionPath() + "/auth-with-password", "POST", queryParams, params);
|
||||
return authResponse(responseData);
|
||||
}
|
||||
|
||||
RecordAuthResponse RecordService::authWithOAuth2(const QString &provider, const QString &code, const QString &codeVerifier, const QString &redirectUrl, const QJsonObject &createData, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("provider", provider);
|
||||
params.insert("code", code);
|
||||
params.insert("codeVerifier", codeVerifier);
|
||||
params.insert("redirectUrl", redirectUrl);
|
||||
params.insert("createData", createData);
|
||||
QJsonObject responseData = client->send(baseCollectionPath() + "/auth-with-oauth2", "POST", queryParams, params);
|
||||
return authResponse(responseData);
|
||||
}
|
||||
|
||||
RecordAuthResponse RecordService::authRefresh(const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject responseData = client->send(baseCollectionPath() + "/auth-refresh", "POST", queryParams, bodyParams);
|
||||
return authResponse(responseData);
|
||||
}
|
||||
|
||||
bool RecordService::requestEmailChange(const QString &newEmail, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("newEmail", newEmail);
|
||||
client->send(baseCollectionPath() + "/request-email-change", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecordService::confirmEmailChange(const QString &token, const QString &password, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("token", token);
|
||||
params.insert("password", password);
|
||||
client->send(baseCollectionPath() + "/confirm-email-change", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecordService::requestPasswordReset(const QString &email, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("email", email);
|
||||
client->send(baseCollectionPath() + "/request-password-reset", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecordService::requestVerification(const QString &email, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("email", email);
|
||||
client->send(baseCollectionPath() + "/request-verification", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecordService::confirmPasswordReset(const QString &passwordResetToken, const QString &password, const QString &passwordConfirm, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("token", passwordResetToken);
|
||||
params.insert("password", password);
|
||||
params.insert("passwordConfirm", passwordConfirm);
|
||||
client->send(baseCollectionPath() + "/confirm-password-reset", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool RecordService::confirmVerification(const QString &token, const QJsonObject &bodyParams, const QUrlQuery &queryParams) {
|
||||
QJsonObject params = bodyParams;
|
||||
params.insert("token", token);
|
||||
client->send(baseCollectionPath() + "/confirm-verification", "POST", queryParams, params);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,101 @@
|
||||
#ifndef RECORDSERVICE_H
|
||||
#define RECORDSERVICE_H
|
||||
|
||||
#include <QString>
|
||||
#include <QUrlQuery>
|
||||
#include <QVariant>
|
||||
#include <QList>
|
||||
#include <QPair>
|
||||
#include <QObject>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include "qpocketbase.h"
|
||||
#include "./utils/crudservice.h"
|
||||
#include "models/recordmodel.hpp"
|
||||
#include "utils/utils.h"
|
||||
#include "baseauthstore.h"
|
||||
|
||||
class RecordService : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
class RecordAuthResponse {
|
||||
public:
|
||||
explicit RecordService(QObject* parent = nullptr, const QString& collectionIdOrName="");
|
||||
QString token;
|
||||
RecordModel record;
|
||||
|
||||
signals:
|
||||
RecordAuthResponse(const QString& token, const RecordModel& record);
|
||||
|
||||
bool isValid() const;
|
||||
|
||||
private:
|
||||
bool validateToken(const QString& token) const;
|
||||
};
|
||||
|
||||
class AuthProviderInfo {
|
||||
public:
|
||||
QString name;
|
||||
QString state;
|
||||
QString codeVerifier;
|
||||
QString codeChallenge;
|
||||
QString codeChallengeMethod;
|
||||
QString authUrl;
|
||||
|
||||
AuthProviderInfo(const QString& name, const QString& state, const QString& codeVerifier,
|
||||
const QString& codeChallenge, const QString& codeChallengeMethod,
|
||||
const QString& authUrl);
|
||||
};
|
||||
|
||||
class AuthMethodsList {
|
||||
public:
|
||||
bool usernamePassword;
|
||||
bool emailPassword;
|
||||
QList<AuthProviderInfo> authProviders;
|
||||
|
||||
AuthMethodsList(bool usernamePassword, bool emailPassword, const QList<AuthProviderInfo>& authProviders);
|
||||
};
|
||||
|
||||
class RecordService : public CrudService {
|
||||
public:
|
||||
QString collectionIdOrName;
|
||||
|
||||
RecordService(std::shared_ptr<QPocketBase> client, const QString& collectionIdOrName);
|
||||
|
||||
std::shared_ptr<BaseModel> decode(const QJsonObject& data) override;
|
||||
|
||||
QString baseCrudPath() const override;
|
||||
|
||||
QString baseCollectionPath() const;
|
||||
|
||||
QString getFileUrl(const RecordModel& record, const QString& filename, const QUrlQuery& queryParams = QUrlQuery()) const;
|
||||
|
||||
void subscribe(std::function<void(const QVariant&)> callback);
|
||||
|
||||
void subscribeOne(const QString& recordId, std::function<void(const QVariant&)> callback);
|
||||
|
||||
void unsubscribe(const QStringList& recordIds);
|
||||
|
||||
RecordModel update(const QString& id, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool deleteRecord(const QString& id, const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
RecordAuthResponse authResponse(const QJsonObject& responseData);
|
||||
|
||||
AuthMethodsList listAuthMethods(const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
RecordAuthResponse authWithPassword(const QString& usernameOrEmail, const QString& password, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
RecordAuthResponse authWithOAuth2(const QString& provider, const QString& code, const QString& codeVerifier, const QString& redirectUrl, const QJsonObject& createData = QJsonObject(), const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
RecordAuthResponse authRefresh(const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool requestEmailChange(const QString& newEmail, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool confirmEmailChange(const QString& token, const QString& password, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool requestPasswordReset(const QString& email, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool requestVerification(const QString& email, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool confirmPasswordReset(const QString& passwordResetToken, const QString& password, const QString& passwordConfirm, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
|
||||
bool confirmVerification(const QString& token, const QJsonObject& bodyParams = QJsonObject(), const QUrlQuery& queryParams = QUrlQuery());
|
||||
};
|
||||
|
||||
#endif // RECORDSERVICE_H
|
||||
|
||||
@@ -24,7 +24,7 @@ ListResult BaseCrudService::_getList(const QString& basePath, int page, int perP
|
||||
params["page"] = page;
|
||||
params["perPage"] = perPage;
|
||||
|
||||
QJsonObject response_data = client->send(basePath, { {"method", "GET"}, {"params", params} }).toObject();
|
||||
QJsonObject response_data; // = client->send(basePath, { {"method", "GET"}, {"params", params} }).toObject();
|
||||
QList<std::shared_ptr<BaseModel>> items;
|
||||
if (response_data.contains("items")) {
|
||||
QJsonArray itemsArray = response_data["items"].toArray();
|
||||
@@ -42,7 +42,8 @@ ListResult BaseCrudService::_getList(const QString& basePath, int page, int perP
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseModel> BaseCrudService::_getOne(const QString& basePath, const QString& id, const QJsonObject& queryParams) {
|
||||
return decode(client->send(QString("%1/%2").arg(basePath, QUrl::toPercentEncoding(id)), { {"method", "GET"}, {"params", queryParams} }).toObject());
|
||||
// return decode(client->send(QString("%1/%2").arg(basePath, QUrl::toPercentEncoding(id)), { {"method", "GET"}, {"params", queryParams} }).toObject());
|
||||
return std::shared_ptr<BaseModel>();
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseModel> BaseCrudService::_getFirstListItem(const QString& basePath, const QString& filter, const QJsonObject& queryParams) {
|
||||
@@ -50,19 +51,22 @@ std::shared_ptr<BaseModel> BaseCrudService::_getFirstListItem(const QString& bas
|
||||
params["filter"] = filter;
|
||||
params["$cancelKey"] = "one_by_filter_" + basePath + "_" + filter;
|
||||
|
||||
ListResult result = getList(basePath, 1, 1, params);
|
||||
if (result.items().isEmpty()) {
|
||||
throw ClientResponseError("The requested resource wasn't found.", 404);
|
||||
}
|
||||
return result.items().first();
|
||||
// ListResult result = getList(basePath, 1, 1, params);
|
||||
// if (result.items().isEmpty()) {
|
||||
// throw ClientResponseError("The requested resource wasn't found.", 404);
|
||||
// }
|
||||
// return result.items().first();
|
||||
return std::shared_ptr<BaseModel>();
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseModel> BaseCrudService::_create(const QString& basePath, const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
return decode(client->send(basePath, { {"method", "POST"}, {"params", queryParams}, {"body", bodyParams} }).toObject());
|
||||
// return decode(client->send(basePath, { {"method", "POST"}, {"params", queryParams}, {"body", bodyParams} }).toObject());
|
||||
return std::shared_ptr<BaseModel>();
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseModel> BaseCrudService::_update(const QString& basePath, const QString& id, const QJsonObject& bodyParams, const QJsonObject& queryParams) {
|
||||
return decode(client->send(QString("%1/%2").arg(basePath, QUrl::toPercentEncoding(id)), { {"method", "PATCH"}, {"params", queryParams}, {"body", bodyParams} }).toObject());
|
||||
// return decode(client->send(QString("%1/%2").arg(basePath, QUrl::toPercentEncoding(id)), { {"method", "PATCH"}, {"params", queryParams}, {"body", bodyParams} }).toObject());
|
||||
return std::shared_ptr<BaseModel>();
|
||||
}
|
||||
|
||||
bool BaseCrudService::_delete(const QString& basePath, const QString& id, const QJsonObject& queryParams) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <QObject>
|
||||
#include <memory>
|
||||
#include <QJsonObject>
|
||||
|
||||
class QPocketBase; // Forward declaration of QPocketBase class
|
||||
|
||||
|
||||
@@ -30,6 +30,6 @@ std::shared_ptr<BaseModel> CrudService::update(const QString& id, const QJsonObj
|
||||
return _update(baseCrudPath(), id, bodyParams, queryParams);
|
||||
}
|
||||
|
||||
bool CrudService::deleteItem(const QString& id, const QJsonObject& queryParams) {
|
||||
bool CrudService::deleteOne(const QString& id, const QJsonObject& queryParams) {
|
||||
return _delete(baseCrudPath(), id, queryParams);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ public:
|
||||
std::shared_ptr<BaseModel> getOne(const QString& id, const QJsonObject& queryParams = QJsonObject());
|
||||
std::shared_ptr<BaseModel> create(const QJsonObject& bodyParams = QJsonObject(), const QJsonObject& queryParams = QJsonObject());
|
||||
std::shared_ptr<BaseModel> update(const QString& id, const QJsonObject& bodyParams = QJsonObject(), const QJsonObject& queryParams = QJsonObject());
|
||||
bool deleteItem(const QString& id, const QJsonObject& queryParams = QJsonObject());
|
||||
bool deleteOne(const QString& id, const QJsonObject& queryParams = QJsonObject());
|
||||
|
||||
protected:
|
||||
virtual QString baseCrudPath() const = 0;
|
||||
|
||||
58
sdk/utils/eventloop.cpp
Normal file
58
sdk/utils/eventloop.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
#include "eventloop.h"
|
||||
#include <QNetworkRequest>
|
||||
#include <QNetworkReply>
|
||||
#include <QUrl>
|
||||
#include <QUrlQuery>
|
||||
|
||||
EventLoop::EventLoop(const QString& url, const QString& method, const QMap<QString, QString>& headers, const QByteArray& payload, const QString& encoding, QObject* parent)
|
||||
: QThread(parent), url(url), method(method), headers(headers), payload(payload), encoding(encoding), kill(false) {}
|
||||
|
||||
void EventLoop::addEventListener(const QString& event, std::function<void(const Event&)> callback) {
|
||||
listeners[event] = callback;
|
||||
}
|
||||
|
||||
void EventLoop::removeEventListener(const QString& event) {
|
||||
listeners.remove(event);
|
||||
}
|
||||
|
||||
void EventLoop::run() {
|
||||
while (!kill) {
|
||||
readStream();
|
||||
}
|
||||
}
|
||||
|
||||
void EventLoop::readStream() {
|
||||
QNetworkRequest request(QUrl{url});
|
||||
for (auto it = headers.begin(); it != headers.end(); ++it) {
|
||||
request.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
|
||||
}
|
||||
|
||||
QNetworkReply* reply = networkManager.sendCustomRequest(request, method.toUtf8(), payload);
|
||||
connect(reply, &QNetworkReply::readyRead, this, [this, reply]() {
|
||||
QByteArray data = reply->readAll();
|
||||
processEvent(data);
|
||||
});
|
||||
|
||||
connect(reply, &QNetworkReply::finished, this, [reply]() {
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
void EventLoop::processEvent(const QByteArray& data) {
|
||||
Event event;
|
||||
QList<QByteArray> lines = data.split('\n');
|
||||
for (const QByteArray& line : lines) {
|
||||
if (line.startsWith("id:")) {
|
||||
event.setId(line.mid(3).trimmed());
|
||||
} else if (line.startsWith("event:")) {
|
||||
event.setEvent(line.mid(6).trimmed());
|
||||
} else if (line.startsWith("data:")) {
|
||||
event.setData(line.mid(5).trimmed());
|
||||
} else if (line.startsWith("retry:")) {
|
||||
event.setRetry(line.mid(6).trimmed().toInt());
|
||||
}
|
||||
}
|
||||
if (listeners.contains(event.getEvent())) {
|
||||
listeners[event.getEvent()](event);
|
||||
}
|
||||
}
|
||||
36
sdk/utils/eventloop.h
Normal file
36
sdk/utils/eventloop.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef EVENTLOOP_H
|
||||
#define EVENTLOOP_H
|
||||
|
||||
#include <QThread>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QMap>
|
||||
#include <functional>
|
||||
#include "../event.h"
|
||||
|
||||
class EventLoop : public QThread {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit EventLoop(const QString& url, const QString& method = "GET", const QMap<QString, QString>& headers = {}, const QByteArray& payload = QByteArray(), const QString& encoding = "utf-8", QObject* parent = nullptr);
|
||||
void addEventListener(const QString& event, std::function<void(const Event&)> callback);
|
||||
void removeEventListener(const QString& event);
|
||||
|
||||
protected:
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
void readStream();
|
||||
void processEvent(const QByteArray& data);
|
||||
|
||||
QString url;
|
||||
QString method;
|
||||
QMap<QString, QString> headers;
|
||||
QByteArray payload;
|
||||
QString encoding;
|
||||
QNetworkAccessManager networkManager;
|
||||
bool kill;
|
||||
QMap<QString, std::function<void(const Event&)>> listeners;
|
||||
};
|
||||
|
||||
#endif // EVENTLOOP_H
|
||||
25
sdk/utils/utils.h
Normal file
25
sdk/utils/utils.h
Normal file
@@ -0,0 +1,25 @@
|
||||
#ifndef UTILS_H
|
||||
#define UTILS_H
|
||||
|
||||
#include <QString>
|
||||
#include <QRegularExpression>
|
||||
#include <QJsonObject>
|
||||
#include <QUrlQuery>
|
||||
|
||||
namespace Utils {
|
||||
QString camelToSnake(const QString &str) {
|
||||
QString result = str;
|
||||
result.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2").toLower();
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject urlQueryToJson(const QUrlQuery &query) {
|
||||
QJsonObject jsonObj;
|
||||
for (const QPair<QString, QString> &item : query.queryItems()) {
|
||||
jsonObj.insert(item.first, item.second);
|
||||
}
|
||||
return jsonObj;
|
||||
}
|
||||
}
|
||||
|
||||
#endif // UTILS_H
|
||||
Reference in New Issue
Block a user