From 94b5365a1cbc91a0d6a9520fd3c9dd73f029a241 Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Mon, 20 Jul 2026 19:24:50 +1000 Subject: [PATCH] likes! --- server/src/db.cpp | 17 ++++++++++++----- server/src/main.cpp | 14 ++++++++------ 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/server/src/db.cpp b/server/src/db.cpp index b4566bf..a6bee59 100644 --- a/server/src/db.cpp +++ b/server/src/db.cpp @@ -23,7 +23,7 @@ Database::Database(const std::string& path) { userid INTEGER NOT NULL, content TEXT NOT NULL, timestamp INTEGER NOT NULL, - likes INTEGER + likes INTEGER NOT NULL DEFAULT 0 ); )"; @@ -158,16 +158,23 @@ void Database::addLike(uint64_t postId, uint64_t userId) { std::stringstream sql; sql << R"( UPDATE posts - SET likes = likes + 1 + SET likes = COALESCE(likes, 0) + 1 WHERE id = )"; sql << postId << ";"; std::string sqlstr = sql.str(); - char* errmsg = nullptr; - if (sqlite3_exec(db, sqlstr.c_str(), nullptr, nullptr, &errmsg) != SQLITE_OK) { - throw std::runtime_error("sqlite3 error: " + std::string(errmsg)); + sqlite3_stmt* stmt; + if (sqlite3_prepare_v2(db, sqlstr.c_str(), -1, &stmt, nullptr) != SQLITE_OK) { + throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db))); } + + if (sqlite3_step(stmt) != SQLITE_DONE) { + throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db))); + } + + sqlite3_finalize(stmt); + } diff --git a/server/src/main.cpp b/server/src/main.cpp index 85d8667..36c686e 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp @@ -104,17 +104,19 @@ int main() { }); svr.Post("/like", [&database, &data_mutex](const httplib::Request& request, httplib::Response& response) { - std::string username = request.get_param_value("username"); - std::string password = request.get_param_value("password"); - std::string post = request.get_param_value("post"); - - std::lock_guard lock(data_mutex); - try { + std::string username = request.form.get_field("username"); + std::string password = request.form.get_field("password"); + std::string post = request.form.get_field("post"); + + std::lock_guard lock(data_mutex); + uint64_t postNum = std::stoull(post); database.addLike(postNum, 0); } catch (const std::runtime_error& e) { response.set_content("

there was an error :( it is: " + std::string(e.what()) + "

", "text/html"); + } catch (const std::exception& e) { + response.set_content("

there was an error :( it is: " + std::string(e.what()) + "

", "text/html"); } });