eedb/src/app/main.cpp
Bartosz Wieczorek e927cd9ba0 fix #11
2018-03-01 09:22:24 +01:00

82 lines
2.6 KiB
C++

#include <spdlog/spdlog.h>
#include <eedb/db/pg/config.hpp>
#include <eedb/db/pg/connection.hpp>
#include <eedb/db/pg/PgCategoriesRepository.hpp>
#include <eedb/db/pg/PgUsers.hpp>
#include <eedb/WebApplicationFactory.hpp>
#include <eedb/WebServer.hpp>
#include <Wt/WApplication.h>
#include <set>
static auto _createSinks() {
std::vector< spdlog::sink_ptr > sinks;
auto stdout_sink = spdlog::sinks::stdout_sink_mt::instance();
auto color_sink = std::make_shared< spdlog::sinks::ansicolor_sink >(stdout_sink);
sinks.push_back(color_sink);
sinks.push_back(std::make_shared< spdlog::sinks::daily_file_sink_st >("logfile", 23, 59));
return sinks;
}
static void initializeLogs() {
std::vector< spdlog::sink_ptr > sinks = _createSinks();
auto combined_logger = std::make_shared< spdlog::logger >("default", begin(sinks), end(sinks));
combined_logger->set_level(spdlog::level::trace);
spdlog::register_logger(combined_logger);
}
static auto createDbConnection(std::function< bool(const std::string &, std::string &) > propRead) {
using std::make_unique;
using std::move;
using std::unique_ptr;
auto dbConfig = make_unique< eedb::db::PgConfig >(propRead);
try {
return make_unique< eedb::db::PgConnection >(std::move(dbConfig));
} catch(const sqlpp::postgresql::broken_connection & e) {
std::cout << "sql exception: " << e.what();
// return std::make_unique< ErrorWindow >(env)
}
}
int main(int argc, char ** argv) {
initializeLogs();
std::set< std::unique_ptr< eedb::db::PgConnection > > activeConnections;
eedb::WebServer server{argc, argv};
server.run([&activeConnections, &server](const auto & env) {
// in order to extend the lifetime of new connection to the lifetime of web application, we need to
// hold it in external container
auto dbIt = activeConnections.emplace(createDbConnection(server.getPropertiesReader())).first;
eedb::WebApplicationFactory factory;
return factory.create(
[&activeConnections, dbIt]() {
// remove connection hold by application from container
spdlog::get("default")->info("Removing database connection from connection list");
activeConnections.erase(dbIt);
},
// users factory
[db = dbIt->get()]() { //
return std::make_unique< eedb::PgUsers >(*db);
},
// categories factory
[db = dbIt->get()](eedb::User * owner) { //
return std::make_unique< eedb::PgCategoriesRepository >(*db, owner);
},
env);
});
return 0;
}