PNP_PIbd-31_Rodionov_I_A_Co.../apiclient.h
2025-01-14 21:33:47 +04:00

65 lines
2.0 KiB
C++

#ifndef APICLIENT_H
#define APICLIENT_H
#include <QtCore>
#include <QtNetwork>
#include <QObject>
#include "models/types.h" // IWYU pragma: keep
class ApiClient : public QObject
{
Q_OBJECT
public:
explicit ApiClient(QObject *parent = nullptr);
void getEntities(const QString &url);
void getFilteredDevices(bool isWorking, double priceFrom, double priceTo, bool applyFilters,
bool disregardState, int entityId, int currentEntity, const QString &searchText,
const QString &sortOrder);
void updateDevice(int id, const Device &device);
signals:
void departmentsReceived(const QMap<int, Department> &departments);
void deviceModelsReceived(const QMap<int, DeviceModel> &deviceModels);
void deviceTypesReceived(const QMap<int, DeviceType> &deviceType);
void locationsReceived(const QMap<int, Location> &locations);
void manufacturersReceived(const QMap<int, Manufacturer> &manufacturers);
void devicesReceived(const QList<Device> &devices);
void deviceUpdated(bool success);
private:
template <typename T>
QMap<int, T> deserializeEntities(const QByteArray &data, const QString &itemsKey);
Device deserializeDevice(const QJsonObject &json);
private slots:
void parseData(QNetworkReply *reply);
void handleDeviceUpdated(QNetworkReply *reply);
void handleError(QNetworkReply::NetworkError error);
private:
const QString baseUrl = "http://localhost:8080";
QNetworkAccessManager *_networkManager;
};
template<typename T>
QMap<int, T> ApiClient::deserializeEntities(const QByteArray &data, const QString &itemsKey)
{
QMap<int, T> entities;
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonArray itemsArray = doc.object().value(itemsKey).toArray();
for (const QJsonValue &value : itemsArray) {
T entity;
entity.fromJson(value.toObject());
entities.insert(entity.id(), entity);
}
return entities;
}
#endif // APICLIENT_H