Обновление cpp-сервера
This commit is contained in:
@@ -14,4 +14,5 @@ target_include_directories(${PROJECT_NAME} PUBLIC include)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
la_json
|
||||
la_storage
|
||||
la_utils
|
||||
)
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace controllers::anomaly_logs::fields {
|
||||
/// @defgroup Поля запроса
|
||||
/// @{
|
||||
constexpr std::string_view last_index = "last_index";
|
||||
/// @}
|
||||
|
||||
/// @defgroup Поля ответа
|
||||
/// @{
|
||||
constexpr std::string_view id = "id";
|
||||
constexpr std::string_view class_id = "class_id";
|
||||
constexpr std::string_view data = "data";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::anomaly_logs::details {
|
||||
struct AnomalyLogRow {
|
||||
int64_t id;
|
||||
int64_t class_id;
|
||||
std::string data;
|
||||
};
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_id);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
namespace fields::anomaly_logs {
|
||||
/// @defgroup Поля запроса anomaly_logs
|
||||
/// @{
|
||||
constexpr const char* last_index = "last_index";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::anomaly_logs {
|
||||
/// @brief Контроллер для обработки запроса получения аномальных логов
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct AnomalyLogRow {
|
||||
int64_t index;
|
||||
std::string data;
|
||||
};
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_index);
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
/// @brief Контроллер для обработки запроса получения аномальных логов
|
||||
class AnomalyLogsController : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit AnomalyLogsController();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
@@ -4,24 +4,32 @@
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
class ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
/// @param[in] name Название контроллера
|
||||
explicit ControllerBase(std::string name);
|
||||
namespace controllers {
|
||||
class ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
/// @param[in] resource Ресурс контроллера
|
||||
/// @param[in] operation Операция контроллера
|
||||
explicit ControllerBase(std::string resource, std::string operation);
|
||||
|
||||
/// @brief Деструктор
|
||||
virtual ~ControllerBase() = default;
|
||||
/// @brief Деструктор
|
||||
virtual ~ControllerBase() = default;
|
||||
|
||||
/// @brief Получение названия контроллера
|
||||
/// @returns Название контроллера
|
||||
[[nodiscard]] const std::string& Name() const;
|
||||
/// @brief Получение ресурса контроллера
|
||||
/// @returns Ресурс контроллера
|
||||
[[nodiscard]] const std::string& Resource() const;
|
||||
|
||||
/// @brief Вызов логики контроллера
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ контроллера
|
||||
virtual json operator()(const json& parameters) const = 0;
|
||||
/// @brief Получение Ресурса контроллера
|
||||
/// @returns Ресурс контроллера
|
||||
[[nodiscard]] const std::string& Operation() const;
|
||||
|
||||
protected:
|
||||
std::string name_; ///< Название контроллера
|
||||
};
|
||||
/// @brief Вызов логики контроллера
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ контроллера
|
||||
virtual json operator()(const json& parameters) const = 0;
|
||||
|
||||
protected:
|
||||
std::string resource_; ///< Ресурс контроллера
|
||||
std::string operation_; ///< Операция контроллера
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,37 +4,33 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
#include <controllers/fields.h>
|
||||
|
||||
/// @brief Диспетчер контроллеров. Отвечает за передачу запроса нужному контроллеру
|
||||
class Dispatcher {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
Dispatcher() = default;
|
||||
namespace controllers {
|
||||
/// @brief Диспетчер контроллеров. Отвечает за передачу запроса нужному контроллеру
|
||||
class Dispatcher {
|
||||
public:
|
||||
using Controllers = std::unordered_map<std::string, std::unique_ptr<ControllerBase>>;
|
||||
|
||||
/// @brief Конструктор
|
||||
Dispatcher() = default;
|
||||
|
||||
/// @brief Добавление контроллера
|
||||
/// @tparam Controller Тип контроллера
|
||||
template <typename Controller>
|
||||
void AddController();
|
||||
|
||||
/// @brief Получение контроллеров
|
||||
/// @returns Контроллеры
|
||||
const Controllers& GetControllers() const;
|
||||
|
||||
private:
|
||||
Controllers controllers_; ///< Контроллеры
|
||||
};
|
||||
|
||||
/// @brief Добавление контроллера
|
||||
/// @tparam Controller Тип контроллера
|
||||
template <typename Controller>
|
||||
void AddController();
|
||||
|
||||
/// @brief Обработка запроса
|
||||
/// @param[in] request Тело запроса
|
||||
/// @returns Тело ответа
|
||||
std::string operator()(const char* request) const;
|
||||
|
||||
private:
|
||||
/// @brief Реализация обработки запроса
|
||||
/// @param[in] request Тело запроса
|
||||
/// @returns Тело ответа
|
||||
json CallImpl(const char* request, std::string& command) const;
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, std::unique_ptr<ControllerBase>> controllers_; ///< Контроллеры
|
||||
};
|
||||
|
||||
template <typename Controller>
|
||||
void Dispatcher::AddController() {
|
||||
auto controller = std::make_unique<Controller>();
|
||||
auto name = controller->Name();
|
||||
controllers_.insert({ std::move(name), std::move(controller) });
|
||||
void Dispatcher::AddController() {
|
||||
auto controller = std::make_unique<Controller>();
|
||||
std::string path = '/' + controller->Resource() + '/' + controller->Operation();
|
||||
controllers_.insert({ std::move(path), std::move(controller) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
/// @brief Поля запроса
|
||||
namespace fields::request {
|
||||
static const char* command = "command"; ///< Название команды / Название контроллера
|
||||
static const char* parameters = "parameters"; ///< Параметры
|
||||
}
|
||||
|
||||
/// @brief Поля ответа
|
||||
namespace fields::response {
|
||||
static const char* command = "command"; ///< Название команды / Название контроллера
|
||||
static const char* status = "status"; ///< Статус ответа (ok/error)
|
||||
static const char* result = "result"; ///< Результат (в случае статуса ok)
|
||||
static const char* error_message = "error_message"; ///< Сообщение об ошибке (в случае статуса error)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
/// @brief Парсинг строки в json
|
||||
/// @param[in] data Строка
|
||||
/// @throws std::runtime_error В случае ошибки парсинга (например, некорректный формат)
|
||||
/// @returns json
|
||||
json ParseJson(const char* data);
|
||||
|
||||
/// @brief Проверка наличия необходимых ключей
|
||||
/// @param[in] json Объект, который надо проверить
|
||||
/// @param[in] fields Необходимые ключи
|
||||
/// @throws std::runtime_error В случае отсутствия хотя бы одного ключа
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields);
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace controllers::logs_classes::fields {
|
||||
/// @defgroup Поля ответа
|
||||
/// @{
|
||||
constexpr std::string_view id = "id";
|
||||
constexpr std::string_view name = "name";
|
||||
constexpr std::string_view description = "description";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::logs_classes::details {
|
||||
struct LogsClassesRow {
|
||||
int64_t id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
std::vector<LogsClassesRow> LogsClassesQuery();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::logs_classes {
|
||||
/// @brief Контроллер для обработки запроса получения классов логов
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::logs_classes {
|
||||
/// @brief Контроллер для обработки запроса обновления класса логов
|
||||
class Put : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Put();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace controllers::statistics::details {
|
||||
struct StatisticsRow {
|
||||
std::string name;
|
||||
size_t value;
|
||||
};
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery();
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
namespace fields::statistics {
|
||||
/// @defgroup Поля запроса statistics
|
||||
/// @{
|
||||
constexpr const char* table = "table";
|
||||
constexpr const char* date = "date";
|
||||
/// @}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
namespace controllers::statistics {
|
||||
/// @brief Контроллер для обработки запроса статистики
|
||||
class Get : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit Get();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <unordered_map>
|
||||
|
||||
/// @brief Алиас для набора данных. Ключ является типом транспорта,
|
||||
/// значение -- массив из 24 чисел, представляющих количество учтённых транспортных средств для каждого часа
|
||||
using Datasets = std::unordered_map<std::string, std::vector<uint16_t>>;
|
||||
|
||||
/// @brief Получение наборов данных из хранилища
|
||||
/// @param[in] table Название таблицы
|
||||
/// @param[in] date Дата
|
||||
/// @returns Наборы данных
|
||||
Datasets GetDatasets(std::string_view table, std::string_view date);
|
||||
|
||||
/// @brief Получение процентного отношения каждого типа
|
||||
/// @param[in] datasets Наборы данных
|
||||
/// @param[in] hour Номер часа
|
||||
/// @returns Процентное отношение
|
||||
std::unordered_map<std::string, double> GetTypesPercentage(const Datasets& datasets, size_t hour);
|
||||
|
||||
/// @brief Распределить количество учтённых транспортных средств указаного типа пропорционально к остальным типам
|
||||
/// @param[in, out] datasets Наборы данных
|
||||
/// @param[in] type_to_distribute Тип, который нужно распределить
|
||||
/// @param[in] stock_type Тип, которому уйдёт излишек из-за неточности при работе с вещественными числами
|
||||
void DistributeType(Datasets& datasets, const std::string& type_to_distribute, const std::string& stock_type);
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct StatisticsRow {
|
||||
std::string name;
|
||||
size_t value;
|
||||
};
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery();
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
/// @brief Контроллер для обработки запроса статистики
|
||||
class StatisticsController : public ControllerBase {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
explicit StatisticsController();
|
||||
|
||||
/// @brief Оператор вызова
|
||||
/// @param[in] parameters Параметры
|
||||
/// @returns Ответ
|
||||
json operator()(const json& parameters) const override;
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/anomaly_logs/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::anomaly_logs::details {
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_id) {
|
||||
std::ostringstream query;
|
||||
query << "select id, class_id, data from anomaly_logs where id > " << last_id << ";";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<AnomalyLogRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
AnomalyLogRow anomaly_log_row{
|
||||
row[0].as<int64_t>(),
|
||||
row[1].as<int64_t>(),
|
||||
row[2].as<std::string>(),
|
||||
};
|
||||
|
||||
result.push_back(std::move(anomaly_log_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <controllers/anomaly_logs/get.h>
|
||||
#include <controllers/anomaly_logs/details/fields.h>
|
||||
#include <controllers/anomaly_logs/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::anomaly_logs;
|
||||
|
||||
Get::Get() : ControllerBase("anomaly_logs", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::last_index });
|
||||
|
||||
auto last_index = parameters[fields::last_index].get<int64_t>();
|
||||
|
||||
auto rows = details::AnomalyLogsQuery(last_index);
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::class_id] = row.class_id;
|
||||
item[fields::data] = std::move(row.data);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/anomaly_logs/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
std::vector<AnomalyLogRow> AnomalyLogsQuery(int64_t last_index) {
|
||||
std::ostringstream query;
|
||||
query << "select id, data from anomaly_logs where id > " << last_index << ";";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<AnomalyLogRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
AnomalyLogRow anomaly_log_row{ row[0].as<int64_t>(), row[1].as<std::string>() };
|
||||
result.push_back(std::move(anomaly_log_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <controllers/implementation.h>
|
||||
#include <controllers/anomaly_logs_controller.h>
|
||||
#include <controllers/anomaly_logs/fields.h>
|
||||
#include <controllers/anomaly_logs/query.h>
|
||||
|
||||
AnomalyLogsController::AnomalyLogsController() : ControllerBase("anomaly_logs") {}
|
||||
|
||||
json AnomalyLogsController::operator()(const json& parameters) const {
|
||||
CheckForRequiredFields(parameters, { fields::anomaly_logs::last_index });
|
||||
|
||||
auto last_index = parameters[fields::anomaly_logs::last_index].get<int64_t>();
|
||||
|
||||
auto rows = AnomalyLogsQuery(last_index);
|
||||
|
||||
json result = json::object();
|
||||
for (const auto& row : rows) {
|
||||
result[std::to_string(row.index)] = row.data;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
#include <controllers/controller_base.h>
|
||||
|
||||
ControllerBase::ControllerBase(std::string name) : name_(std::move(name)) {}
|
||||
using namespace controllers;
|
||||
|
||||
const std::string& ControllerBase::Name() const {
|
||||
return name_;
|
||||
ControllerBase::ControllerBase(std::string resource, std::string operation)
|
||||
: resource_(std::move(resource))
|
||||
, operation_(std::move(operation))
|
||||
{}
|
||||
|
||||
const std::string& ControllerBase::Resource() const {
|
||||
return resource_;
|
||||
}
|
||||
|
||||
const std::string& ControllerBase::Operation() const {
|
||||
return operation_;
|
||||
}
|
||||
|
||||
@@ -1,52 +1,7 @@
|
||||
#include <controllers/dispatcher.h>
|
||||
#include <controllers/implementation.h>
|
||||
|
||||
std::string Dispatcher::operator()(const char* request) const {
|
||||
// todo: формирование успешного и ошибочного ответов
|
||||
using namespace controllers;
|
||||
|
||||
std::string command;
|
||||
json result;
|
||||
try {
|
||||
result = CallImpl(request, command);
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "error";
|
||||
json[fields::response::error_message] = e.what();
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
json json;
|
||||
json[fields::response::command] = command;
|
||||
json[fields::response::status] = "ok";
|
||||
json[fields::response::result] = result;
|
||||
|
||||
result = json.dump();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
json Dispatcher::CallImpl(const char* request, std::string& command) const {
|
||||
// Проверяем корректность формата запроса
|
||||
auto json = ParseJson(request);
|
||||
|
||||
// Проверяем наличие необходимых ключей
|
||||
CheckForRequiredFields(json, { fields::request::command, fields::request::parameters });
|
||||
|
||||
// Проверяем наличие команды с указанным именем
|
||||
command = json[fields::request::command].get<std::string>();
|
||||
if (!controllers_.count(command)) {
|
||||
return "unknown command '" + command + "'";
|
||||
}
|
||||
|
||||
// Получаем команду по имени
|
||||
const auto& controller = *controllers_.at(command);
|
||||
|
||||
// Формируем и возвращаем ответ
|
||||
auto parameters = json[fields::request::parameters];
|
||||
return controller(parameters);
|
||||
const Dispatcher::Controllers& Dispatcher::GetControllers() const {
|
||||
return controllers_;
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <controllers/implementation.h>
|
||||
|
||||
json ParseJson(const char* data) {
|
||||
json json;
|
||||
try {
|
||||
json = json::parse(data);
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("failed to parse request");
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
void CheckForRequiredFields(const json& json, std::initializer_list<std::string_view> fields) {
|
||||
for (const auto& field : fields)
|
||||
if (!json.contains(field)) {
|
||||
std::ostringstream message;
|
||||
message << "request doesn't contain required field '" << field << "'";
|
||||
throw std::runtime_error(message.str());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::logs_classes::details {
|
||||
std::vector<LogsClassesRow> LogsClassesQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select id, name, description from logs_classes;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<LogsClassesRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
LogsClassesRow logs_classes_row{
|
||||
row[0].as<int64_t>(),
|
||||
row[1].as<std::string>(),
|
||||
row[2].as<std::string>(),
|
||||
};
|
||||
|
||||
result.push_back(std::move(logs_classes_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#include <controllers/logs_classes/get.h>
|
||||
#include <controllers/logs_classes/details/fields.h>
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::logs_classes;
|
||||
|
||||
Get::Get() : ControllerBase("logs_classes", "put") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::description });
|
||||
|
||||
|
||||
details::LogsClassesQuery();
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::name] = std::move(row.name);
|
||||
item[fields::description] = std::move(row.description);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#include <controllers/logs_classes/put.h>
|
||||
#include <controllers/logs_classes/details/fields.h>
|
||||
#include <controllers/logs_classes/details/query.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
using namespace controllers::logs_classes;
|
||||
|
||||
Get::Get() : ControllerBase("logs_classes", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
auto rows = details::LogsClassesQuery();
|
||||
|
||||
json result = json::array();
|
||||
for (auto& row : rows) {
|
||||
json item = json::object();
|
||||
item[fields::id] = row.id;
|
||||
item[fields::name] = std::move(row.name);
|
||||
item[fields::description] = std::move(row.description);
|
||||
|
||||
result.push_back(std::move(item));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/statistics/details/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
namespace controllers::statistics::details {
|
||||
std::vector<StatisticsRow> StatisticsQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select name, value from statistics;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<StatisticsRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
StatisticsRow statistics_row{ row[0].as<std::string>(), row[1].as<size_t>() };
|
||||
result.push_back(std::move(statistics_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#include <controllers/statistics/get.h>
|
||||
#include <controllers/statistics/details/query.h>
|
||||
|
||||
using namespace controllers::statistics;
|
||||
|
||||
Get::Get() : ControllerBase("statistics", "get") {}
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
auto rows = details::StatisticsQuery();
|
||||
|
||||
json result;
|
||||
for (auto& row : rows) {
|
||||
result[std::move(row.name)] = row.value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <controllers/statistics/query.h>
|
||||
#include <storage/postgresql/postgresql_storage.h>
|
||||
|
||||
std::vector<StatisticsRow> StatisticsQuery() {
|
||||
std::ostringstream query;
|
||||
query << "select name, value from statistics;";
|
||||
|
||||
auto pqxx_result = PostgreSqlStorage::Get().Do(query.str());
|
||||
|
||||
std::vector<StatisticsRow> result;
|
||||
result.reserve(pqxx_result.size());
|
||||
|
||||
for (const auto& row : pqxx_result) {
|
||||
StatisticsRow statistics_row{ row[0].as<std::string>(), row[1].as<size_t>() };
|
||||
result.push_back(std::move(statistics_row));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#include <controllers/implementation.h>
|
||||
#include <controllers/statistics_controller.h>
|
||||
#include <controllers/statistics/query.h>
|
||||
|
||||
StatisticsController::StatisticsController() : ControllerBase("statistics") {}
|
||||
|
||||
json StatisticsController::operator()(const json& parameters) const {
|
||||
auto rows = StatisticsQuery();
|
||||
|
||||
json result;
|
||||
for (const auto& row : rows) {
|
||||
result[row.name] = row.value;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
Reference in New Issue
Block a user