Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UsersServer #10

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open

UsersServer #10

wants to merge 17 commits into from

Conversation

lerakrya8
Copy link
Collaborator

No description provided.

Copy link
Collaborator

@Vinograduss Vinograduss left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У вас у всех один и тот же код, одни и те же ошибки. кажется я проверяю один код уже который раз )

project/includes/Server.h project/src/UsersDatabase.cpp)


target_link_directories(ServerUsers PUBLIC project/includes/)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у тебя же переменная для INC_DIR может стоит ее использовать? или зачем ты ее вводил?

}
}

void server(boost::asio::io_service& io_service, unsigned short port)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем создавать отдельно io_service и передавать в эту функцию в качестве параметра?

using std::string;
using boost::property_tree::ptree;

std::map<string, string> HandlerUser::parser_json(std::stringstream& request) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет смысла принимать stringstream в качестве аргумента, ведь у тебя по сути везде используются строки

if (!request.str().empty()) {
boost::property_tree::read_json(request, pt);
std::map<string, string> result;
ptree::const_iterator end = pt.end();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем создавать эту переменную отдельно? может стоит pt.end() использовать в цикле?

int insert_user(std::map<string, string>& users_data) {
string sql_request("INSERT INTO Users VALUES(");
int i = 0;
for(auto& string : users_data) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

string не стоит использовать ключевые слова языка для цикла

boost::asio::io_service& io_service_;
boost::asio::ip::tcp::socket socket_;
int max_length = 1024;
char data_[1024];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем в каждом экземпляре инициализировать переменную int max_length ?
лучше сделать глобальную static переменную

если ты вводишь переменную для размера массива, то стоит использовать для инициализации размера массива

#include <string>
#include <map>
#include <pqxx/pqxx>
#include "Database.h"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишние инклюды

~UsersDatabase() override;
int insert_(const std::map<std::string, std::string>& users_data) override;
const std::string data_user(int id);
const std::string all_users();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

какой смысл возвращать из функции 'const string', разумнее обозначать методы, которые не меняют не меняют состояние объект `std::string all_users() const'

void Session::send_answer(std::string& answer) {
std::cout << "ООТвет " << answer << std::endl;
boost::asio::io_service service;
tcp::endpoint end(boost::asio::ip::address::from_string("127.0.0.1"), 8888);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у тебя создается io_service для каждого соединения что не очень хорошо

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

надо вынести в параметры или конфиг


W.exec( sql_request );
W.commit();
return 200;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужна обертка для работы с БД

@lerakrya8
Copy link
Collaborator Author

Снимок экрана от 2020-12-24 23-37-39

project(ServerUsers)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-lpqxx -lpq")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Запуск без флагов -Wall -Werror -Wpedantic

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

поняла, спасибо!


set(TESTS_DIR ${DIR}tests)

include_directories(project/includes/)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше использовать target_include_directories

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошо


include_directories(project/includes/)

add_library(ServerUsers STATIC ${SRC_DIR}/Session.cpp ${SRC_DIR}/HandlerUser.cpp

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше создавать библиотеку внутри директории с исходниками и делать add_subdirectory

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

запомню на будущее


add_executable(test_server test_server.cpp)

add_executable(TESTS project/tests.cpp)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тесты должны быть в отдельной директории со своим симейком

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

спасибо!

tcp::endpoint end(boost::asio::ip::address::from_string("127.0.0.1"), 8082);
tcp::socket socket(service);
socket.async_connect(end, [&socket] (const boost::system::error_code& err) {
// std::string requst = "123\napi/users/create/\n-1\n\n{\n"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Убрать закомменченный код, ему не место на репозитории

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хорошо

std::map<string, string> result;
for (ptree::const_iterator it = pt.begin(); it != pt.end(); ++it) {
string field = std::string(it->first);
if (std::string(it->first) == "id") {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

почему нет сущности, хранящей названия полей?

request += "\n \"password\": \"" + data_user.at("password") + "\",\n \"login\": \"" + data_user.at("Eemail") + "\"\n}";

boost::asio::io_service service;
boost::asio::ip::tcp::endpoint end(boost::asio::ip::address::from_string("127.0.0.1"), 9999);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

захардкоженный урл

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

согласна

request += std::to_string(data_base_.get_id());
request += "\n \"password\": \"" + data_user.at("password") + "\",\n \"login\": \"" + data_user.at("Eemail") + "\"\n}";

boost::asio::io_service service;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

постоянно создается клиент, не поддерживается постоянное соединение

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

чтобы это проблему исправить, пришлось бы менять архитектуру, а на это уже не было времени

try {
data_base_.all_users();
string result = std::to_string(number_request) + "\n";
string new_result = data_base_.all_users();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

дважды вызывается функция

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

спасибо

data_base_.all_users();
string result = std::to_string(number_request) + "\n";
string new_result = data_base_.all_users();
if (new_result == "No users") {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно было бы сделать сущность, хранящую ответы от БД

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, спасибо

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants