75 lines
No EOL
2.6 KiB
C++
75 lines
No EOL
2.6 KiB
C++
#include <string>
|
|
|
|
#include "crow.h"
|
|
#include <pqxx/pqxx>
|
|
|
|
#include "crow/http_response.h"
|
|
#include "dotenv.hpp"
|
|
#include "json.hpp"
|
|
|
|
pqxx::connection* globalConnection(nullptr);
|
|
crow::response test(void);
|
|
crow::response getSimplePosts(int limit);
|
|
|
|
// Json Handler with a precise data type
|
|
Etheryo::JsonHandler category;
|
|
Etheryo::JsonHandler post_info;
|
|
|
|
int main()
|
|
{
|
|
// Init Json Objects
|
|
category.add({ "id", "slug", "icon", "type_icon" });
|
|
post_info.add({"slug","author","title", "date", "picture"});
|
|
|
|
// Init Postgresql + DotEnv
|
|
Etheryo::DotEnv dotenvParser;
|
|
dotenvParser.readFile("res/.env");
|
|
globalConnection = new pqxx::connection(dotenvParser["DATABASE_URL"]);
|
|
std::cout << "Connected to " << globalConnection->dbname() << '\n';
|
|
|
|
// Init Crow App
|
|
crow::SimpleApp app;
|
|
CROW_ROUTE(app, "/")(test);
|
|
CROW_ROUTE(app, "/get_simple_posts/<int>")(getSimplePosts);
|
|
|
|
app.port(8000).multithreaded().run();
|
|
globalConnection->close();
|
|
}
|
|
|
|
crow::response test(void)
|
|
{
|
|
category.clear();
|
|
pqxx::work worker { *globalConnection };
|
|
auto result = worker.query<int, std::string, std::string, std::string>("select c.id, c.slug, c.icon, c.type_icon FROM category c ORDER BY c.id;");
|
|
for (auto [id, slug, icon, type_icon] : result) {
|
|
category["id"] = std::to_string(id);
|
|
category["slug"] = slug;
|
|
category["icon"] = icon;
|
|
category["type_icon"] = type_icon;
|
|
category.push();
|
|
}
|
|
auto response = crow::response { "application/json", category.to_str() };
|
|
response.add_header("Access-Control-Allow-Origin", "*");
|
|
response.add_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
|
return response;
|
|
}
|
|
|
|
crow::response getSimplePosts(int limit)
|
|
{
|
|
post_info.clear();
|
|
pqxx::work worker { *globalConnection };
|
|
auto result = worker.query<std::string, int, std::string, std::string, std::string, std::string>("select p.slug, p.author_id, a.\"name\", p.title, p.\"date\", p.picture from post p join authors a on p.author_id = a.id order by p.\"date\" limit "+std::to_string(limit)+";");
|
|
for(auto [slug, author_id, author_name, title, date, picture] : result)
|
|
{
|
|
post_info["slug"] = slug;
|
|
post_info["author"] = author_name;
|
|
post_info["title"] = title;
|
|
post_info["date"] = date;
|
|
post_info["picture"] = picture;
|
|
post_info.push();
|
|
}
|
|
auto response = crow::response { "application/json", post_info.to_str() };
|
|
response.add_header("Access-Control-Allow-Origin", "*");
|
|
response.add_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
|
return response;
|
|
} |