PNP_PIbd-31_Rodionov_I_A_Co.../apiserver.cpp
2025-01-14 21:28:06 +04:00

238 lines
8.3 KiB
C++

#include "apiserver.h"
ApiServer::ApiServer() {
_server.route("/api/devices", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetFilteredDevices(request);
});
_server.route("/api/departments", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDepartments(request);
});
_server.route("/api/devicemodels", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDeviceModels(request);
});
_server.route("/api/devicetypes", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllDeviceTypes(request);
});
_server.route("/api/locations", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllLocations(request);
});
_server.route("/api/manufacturers", QHttpServerRequest::Method::Get,
[this](const QHttpServerRequest &request) {
return handleGetAllManufacturers(request);
});
_server.route("/api/devices/<arg>", QHttpServerRequest::Method::Put,
[this](int id, const QHttpServerRequest &request) {
return handleUpdateDevice(id, request);
});
}
void ApiServer::start(ServiceLoadDB *serviceDB)
{
_server.listen(QHostAddress::LocalHost, 8080);
_deviceLogic = new DeviceLogic(serviceDB);
_departmentLogic = new DepartmentLogic(serviceDB);
_deviceModelLogic = new DeviceModelLogic(serviceDB);
_locationLogic = new LocationLogic(serviceDB);
_manufacturerLogic = new ManufacturerLogic(serviceDB);
_deviceTypeLogic = new DeviceTypeLogic(serviceDB);
}
QHttpServerResponse ApiServer::handleGetFilteredDevices(const QHttpServerRequest &request)
{
QUrlQuery query = request.query();
bool isWorking = getQueryParamWithDefault(query, "isWorking", true);
double priceFrom = getQueryParamWithDefault(query, "priceFrom", 0.00);
double priceTo = getQueryParamWithDefault(query, "priceTo", std::numeric_limits<double>::max());
bool applyFilters = getQueryParamWithDefault(query, "applyFilters", false);
bool disregardState = getQueryParamWithDefault(query, "disregardState", true);
int entityId = getQueryParamWithDefault(query, "entityId", -1);
int currentEntity = getQueryParamWithDefault(query, "currentEntity", 0);
QString searchText = getQueryParamWithDefault(query, "searchText", QString());
QString sortOrder = getQueryParamWithDefault(query, "sortOrder", QString("Сначала новые"));
if (!validEntityTypeNumbers.contains(currentEntity)) {
currentEntity = 0;
}
if (!validSortOrders.contains(sortOrder)) {
sortOrder = "Сначала новые";
}
FilterParams filterParams;
filterParams.setIsWorking(isWorking);
filterParams.setPriceFrom(priceFrom);
filterParams.setPriceTo(priceTo);
filterParams.setApllyFilters(applyFilters);
filterParams.setDisregardState(disregardState);
QList<Device> filteredDevices = _deviceLogic->getAllByParameters(
entityId,
static_cast<EntityType>(currentEntity),
searchText,
filterParams,
sortOrder
);
QJsonArray deviceArray;
for (const Device &device : filteredDevices) {
deviceArray.append(device.toJson());
}
QJsonObject responseObject;
responseObject["devices"] = deviceArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleGetAllDepartments(const QHttpServerRequest &request)
{
QMap<int, Department> departments = _departmentLogic->getAll();
if (departments.isEmpty()) {
return QHttpServerResponse("Failed to retrieve departments", QHttpServerResponse::StatusCode::InternalServerError);
}
QJsonArray departmentArray = createJsonArray(departments);
QJsonObject responseObject;
responseObject["departments"] = departmentArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleGetAllDeviceModels(const QHttpServerRequest &request)
{
QMap<int, DeviceModel> deviceModels = _deviceModelLogic->getAll();
if (deviceModels.isEmpty()) {
return QHttpServerResponse("Failed to retrieve device models", QHttpServerResponse::StatusCode::InternalServerError);
}
QJsonArray deviceModelArray = createJsonArray(deviceModels);
QJsonObject responseObject;
responseObject["deviceModels"] = deviceModelArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleGetAllDeviceTypes(const QHttpServerRequest &request)
{
QMap<int, DeviceType> deviceTypes = _deviceTypeLogic->getAll();
if (deviceTypes.isEmpty()) {
return QHttpServerResponse("Failed to retrieve device types", QHttpServerResponse::StatusCode::InternalServerError);
}
QJsonArray deviceTypeArray = createJsonArray(deviceTypes);
QJsonObject responseObject;
responseObject["deviceTypes"] = deviceTypeArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleGetAllLocations(const QHttpServerRequest &request)
{
QMap<int, Location> locations = _locationLogic->getAll();
if (locations.isEmpty()) {
return QHttpServerResponse("Failed to retrieve locations", QHttpServerResponse::StatusCode::InternalServerError);
}
QJsonArray locationArray = createJsonArray(locations);
QJsonObject responseObject;
responseObject["locations"] = locationArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleGetAllManufacturers(const QHttpServerRequest &request)
{
QMap<int, Manufacturer> manufacturers = _manufacturerLogic->getAll();
if (manufacturers.isEmpty()) {
return QHttpServerResponse("Failed to retrieve manufacturers", QHttpServerResponse::StatusCode::InternalServerError);
}
QJsonArray manufacturerArray = createJsonArray(manufacturers);
QJsonObject responseObject;
responseObject["manufacturers"] = manufacturerArray;
return QHttpServerResponse(QJsonDocument(responseObject).toJson(), QHttpServerResponse::StatusCode::Ok);
}
QHttpServerResponse ApiServer::handleUpdateDevice(int id, const QHttpServerRequest &request)
{
QByteArray body = request.body();
QJsonDocument doc = QJsonDocument::fromJson(body);
if (!doc.isObject()) {
return QHttpServerResponse("Invalid JSON", QHttpServerResponse::StatusCode::BadRequest);
}
QJsonObject jsonObject = doc.object();
Device device;
device.fromJson(jsonObject);
device.setId(id);
if (!_deviceLogic->updateDevice(device)) {
return QHttpServerResponse("Failed to update device", QHttpServerResponse::StatusCode::InternalServerError);
}
return QHttpServerResponse("Device updated successfully", QHttpServerResponse::StatusCode::Ok);
}
template<typename T>
QJsonArray ApiServer::createJsonArray(const QMap<int, T> &items)
{
QJsonArray itemArray;
for (const T &item : items) {
itemArray.append(item.toJson());
}
return itemArray;
}
template<typename T>
T ApiServer::getQueryParamWithDefault(const QUrlQuery &query, const QString &paramName, const T &defaultValue)
{
QString value = query.queryItemValue(paramName);
if (value.isEmpty()) {
return defaultValue;
}
if constexpr (std::is_same<T, bool>::value) {
return value == "true";
}
if constexpr (std::is_same<T, int>::value) {
bool ok;
int result = value.toInt(&ok);
return ok ? result : defaultValue;
}
if constexpr (std::is_same<T, double>::value) {
bool ok;
double result = value.toDouble(&ok);
return ok ? result : defaultValue;
}
if constexpr (std::is_same<T, QString>::value) {
return value;
}
return defaultValue;
}