Обновление контроллеров и хранилища
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
#include <controllers/anomaly_logs/get.h>
|
||||
#include <data_models/anomaly_logs.h>
|
||||
#include <storage/transaction.h>
|
||||
#include <storage/storage.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
#include "details/fields.h"
|
||||
@@ -12,13 +12,14 @@ json Get::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::last_id });
|
||||
|
||||
// Создаём транзакцию
|
||||
auto transaction = storage::Transaction::Create();
|
||||
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||
|
||||
// Создаём модель
|
||||
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
||||
|
||||
// Запрашиваем логи
|
||||
auto anomaly_logs = anomaly_logs_model.GetAll(parameters[fields::last_id]);
|
||||
auto last_id = std::stoull(parameters[fields::last_id].get<std::string>());
|
||||
auto anomaly_logs = anomaly_logs_model.GetAll(last_id);
|
||||
|
||||
// Формируем ответ
|
||||
json result = json::array();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <controllers/anomaly_logs/update_cluster_id.h>
|
||||
#include <data_models/anomaly_logs.h>
|
||||
#include <storage/transaction.h>
|
||||
#include <storage/storage.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
#include "details/fields.h"
|
||||
@@ -12,7 +12,7 @@ json UpdateClusterId::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::cluster_id });
|
||||
|
||||
// Создаём транзакцию
|
||||
auto transaction = storage::Transaction::Create();
|
||||
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||
|
||||
// Создаём модель
|
||||
data_models::AnomalyLogsModel anomaly_logs_model(transaction);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <controllers/logs_clusters/create.h>
|
||||
#include <data_models/logs_clusters.h>
|
||||
#include <storage/transaction.h>
|
||||
#include <storage/storage.h>
|
||||
#include <utils/utils.h>
|
||||
|
||||
#include "details/fields.h"
|
||||
@@ -12,7 +12,7 @@ json Create::operator()(const json& parameters) const {
|
||||
utils::CheckForRequiredFields(parameters, { fields::id, fields::name, fields::description, fields::recommendation });
|
||||
|
||||
// Создаём транзакцию
|
||||
auto transaction = storage::Transaction::Create();
|
||||
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||
|
||||
// Создаём модель
|
||||
data_models::LogsClustersModel logs_clusters_model(transaction);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <controllers/logs_clusters/get.h>
|
||||
#include <data_models/logs_clusters.h>
|
||||
#include <storage/transaction.h>
|
||||
#include <storage/storage.h>
|
||||
|
||||
#include "details/fields.h"
|
||||
|
||||
@@ -8,7 +8,7 @@ using namespace controllers::logs_clusters;
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
// Создаём транзакцию
|
||||
auto transaction = storage::Transaction::Create();
|
||||
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||
|
||||
// Создаём модель
|
||||
data_models::LogsClustersModel logs_clusters_model(transaction);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
#include <controllers/statistics/get.h>
|
||||
#include <data_models/statistics.h>
|
||||
#include <storage/transaction.h>
|
||||
#include <storage/storage.h>
|
||||
|
||||
using namespace controllers::statistics;
|
||||
|
||||
json Get::operator()(const json& parameters) const {
|
||||
// Создаём транзакцию
|
||||
auto transaction = storage::Transaction::Create();
|
||||
auto transaction = storage::Storage::Get().CreateTransaction();
|
||||
|
||||
// Создаём модель
|
||||
data_models::StatisticsModel statistics_model(transaction);
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
#include <userver/server/handlers/http_handler_base.hpp>
|
||||
|
||||
#include <json/json.h>
|
||||
|
||||
#include "details.h"
|
||||
#include "traits.h"
|
||||
|
||||
@@ -23,7 +25,8 @@ namespace server::details {
|
||||
/// @param[in] context Контекст
|
||||
/// @returns Ответ
|
||||
std::string HandleRequestThrow(const userver::server::http::HttpRequest& request, userver::server::request::RequestContext&) const override {
|
||||
return server::details::HandleRequest(controller_, request.RequestBody());
|
||||
auto request_body = server::details::GetRequestBody(request);
|
||||
return server::details::HandleRequest(controller_, request_body);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -5,40 +5,42 @@
|
||||
|
||||
#include "fields.h"
|
||||
|
||||
namespace {
|
||||
json HandleRequestImpl(const controllers::ControllerBase& controller, const std::string& request) {
|
||||
using namespace server::details;
|
||||
|
||||
// Проверяем корректность формата запроса
|
||||
auto json = ParseJson(request);
|
||||
|
||||
// Проверяем наличие необходимых ключей
|
||||
utils::CheckForRequiredFields(json, { fields::parameters });
|
||||
|
||||
// Формируем и возвращаем ответ
|
||||
auto parameters = json[fields::parameters];
|
||||
return controller(parameters);
|
||||
}
|
||||
}
|
||||
|
||||
namespace server::details {
|
||||
json ParseJson(const std::string& data) {
|
||||
json json;
|
||||
try {
|
||||
json = json::parse(data);
|
||||
} catch (const std::exception& e) {
|
||||
throw std::runtime_error("failed to parse request");
|
||||
throw std::runtime_error("failed to parse json, details: " + std::string(e.what()));
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
std::string HandleRequest(const controllers::ControllerBase& controller, const std::string& request) {
|
||||
Logger::Get().Write(LogLevel::Info, "accepted request '" + request + "'");
|
||||
json GetRequestBody(const userver::server::http::HttpRequest& request) {
|
||||
json body;
|
||||
|
||||
if (!request.RequestBody().empty() && request.RequestBody() != "null") {
|
||||
body = json::parse(request.RequestBody());
|
||||
}
|
||||
|
||||
for (const auto& argument_name : request.ArgNames()) {
|
||||
if (body.contains(argument_name)) {
|
||||
throw std::runtime_error("body already has parameter '" + argument_name + "'");
|
||||
}
|
||||
|
||||
body[argument_name] = request.GetArg(argument_name);
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
std::string HandleRequest(const controllers::ControllerBase& controller, const json& request) {
|
||||
Logger::Get().Write(LogLevel::Info, "accepted request '" + request.dump() + "'");
|
||||
|
||||
json result;
|
||||
try {
|
||||
result = HandleRequestImpl(controller, request);
|
||||
result = controller(request);
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
json json;
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <userver/server/http/http_request.hpp>
|
||||
|
||||
#include <controllers/controller_base.h>
|
||||
#include <json/json.h>
|
||||
|
||||
namespace server::details {
|
||||
/// @brief Парсинг строки в json
|
||||
@@ -7,9 +12,14 @@ namespace server::details {
|
||||
/// @returns json
|
||||
json ParseJson(const std::string& data);
|
||||
|
||||
/// @brief Получение тела запроса
|
||||
/// @param[in] request Запрос
|
||||
/// @returns Тело запроса
|
||||
json GetRequestBody(const userver::server::http::HttpRequest& request);
|
||||
|
||||
/// @brief Обработка запроса
|
||||
/// @param[in] controller Контроллер
|
||||
/// @param[in] request Запрос
|
||||
/// @returns Ответ
|
||||
std::string HandleRequest(const controllers::ControllerBase& controller, const std::string& request);
|
||||
std::string HandleRequest(const controllers::ControllerBase& controller, const json& request);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ StorageWrapper::StorageWrapper(const userver::components::ComponentConfig& confi
|
||||
connection_data.host = config["host"].As<std::string>();
|
||||
connection_data.port = config["port"].As<std::string>();
|
||||
|
||||
storage::Storage::Connect(connection_data);
|
||||
storage::Storage::Get().Connect(connection_data);
|
||||
}
|
||||
|
||||
userver::yaml_config::Schema StorageWrapper::GetStaticConfigSchema() {
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
#include <pqxx/pqxx>
|
||||
|
||||
#include <storage/transaction.h>
|
||||
|
||||
namespace storage {
|
||||
@@ -22,11 +20,13 @@ namespace storage {
|
||||
|
||||
/// @brief Подключение к хранилищу
|
||||
/// @param[in] connection_data Данных подключения
|
||||
static void Connect(const ConnectionData& connection_data);
|
||||
void Connect(const ConnectionData& connection_data);
|
||||
|
||||
friend class Transaction;
|
||||
/// @brief Создание транзацкии
|
||||
/// @returns Транзакция
|
||||
Transaction CreateTransaction();
|
||||
|
||||
private:
|
||||
std::unique_ptr<pqxx::connection> connection_; ///< Соединение
|
||||
std::string connection_data_; ///< Данные подключения
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
#include <memory>
|
||||
|
||||
#include <pqxx/pqxx>
|
||||
|
||||
@@ -8,6 +9,9 @@ namespace storage {
|
||||
/// @brief Транзакция
|
||||
class Transaction {
|
||||
public:
|
||||
/// @brief Конструктор
|
||||
Transaction(const std::string& connection_data);
|
||||
|
||||
/// @brief Деструктор
|
||||
~Transaction();
|
||||
|
||||
@@ -17,21 +21,13 @@ namespace storage {
|
||||
/// @brief Оператор перемещающего присваивания
|
||||
Transaction& operator=(Transaction&&) = default;
|
||||
|
||||
/// @brief Создание транзацкии
|
||||
/// @pre Должно быть установлено соединение с хранилищем
|
||||
/// @returns Транзакция
|
||||
static Transaction Create();
|
||||
|
||||
/// @brief Выполнение запроса
|
||||
/// @param[in] query Запрос
|
||||
/// @returns Результат выполнения
|
||||
pqxx::result Do(std::string_view query) const;
|
||||
|
||||
private:
|
||||
/// @brief Конструктор
|
||||
Transaction() = default;
|
||||
|
||||
private:
|
||||
std::unique_ptr<pqxx::connection> connection_; ///< Соединение
|
||||
std::unique_ptr<pqxx::work> transaction_; ///< Транзакция
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,12 +10,16 @@ Storage& Storage::Get() {
|
||||
}
|
||||
|
||||
void Storage::Connect(const ConnectionData& connection_data) {
|
||||
std::ostringstream options;
|
||||
options << "dbname = " << connection_data.database
|
||||
std::ostringstream connection;
|
||||
connection << "dbname = " << connection_data.database
|
||||
<< " user = " << connection_data.username
|
||||
<< " password = " << connection_data.password
|
||||
<< " host = " << connection_data.host
|
||||
<< " port = " << connection_data.port;
|
||||
|
||||
Get().connection_ = std::make_unique<pqxx::connection>(options.str());
|
||||
connection_data_ = connection.str();
|
||||
}
|
||||
|
||||
Transaction Storage::CreateTransaction() {
|
||||
return { connection_data_ };
|
||||
}
|
||||
|
||||
@@ -1,23 +1,20 @@
|
||||
#include <sstream>
|
||||
|
||||
#include <storage/storage.h>
|
||||
#include <storage/transaction.h>
|
||||
|
||||
using namespace storage;
|
||||
|
||||
Transaction::Transaction(const std::string& connection_data)
|
||||
: connection_(std::make_unique<pqxx::connection>(connection_data))
|
||||
, transaction_(std::make_unique<pqxx::work>(*connection_)) {}
|
||||
|
||||
Transaction::~Transaction() {
|
||||
transaction_->commit();
|
||||
}
|
||||
|
||||
Transaction Transaction::Create() {
|
||||
auto& storage = storage::Storage::Get();
|
||||
|
||||
Transaction transaction;
|
||||
transaction.transaction_ = std::make_unique<pqxx::work>(*storage.connection_);
|
||||
|
||||
return transaction;
|
||||
if (connection_ && transaction_) {
|
||||
transaction_->commit();
|
||||
connection_->close();
|
||||
}
|
||||
}
|
||||
|
||||
pqxx::result Transaction::Do(std::string_view query) const {
|
||||
return transaction_->exec(query);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user