From 00ac999983c9fa532b40190415e3d8f8d328ae9c Mon Sep 17 00:00:00 2001 From: SuperNovaa41 Date: Wed, 24 Jan 2024 10:54:38 -0500 Subject: [PATCH] Adds an endpoint to add books - Changed the release version for ISBN-lookup because it was out of date and broke a feature - Added an endpoint for adding books with robust error handling --- api/isbn-interaction.cpp | 36 ++++++++++++++++++++++++++++-------- api/isbn-interaction.h | 2 +- api/main.cpp | 11 ++++++++++- compile.sh | 2 +- 4 files changed, 40 insertions(+), 11 deletions(-) diff --git a/api/isbn-interaction.cpp b/api/isbn-interaction.cpp index 9bc259b..a2696ce 100644 --- a/api/isbn-interaction.cpp +++ b/api/isbn-interaction.cpp @@ -1,9 +1,10 @@ -#include #include #include #include +#include #include +#include #include "isbn-interaction.h" #include "csv.h" @@ -14,6 +15,7 @@ std::string book_vec_to_json(std::vector headers, std::vector book_vec; std::vector header_vec; + file.open(BOOK_FILENAME); if (!file.good()) { @@ -45,25 +48,42 @@ std::string get_all_books() total_lines = "{"; while (std::getline(file, line)) { book_vec = get_csv_as_vector(line); + total_lines += book_vec_to_json(header_vec, book_vec) + ","; } + return total_lines + "}"; } -void add_new_book(std::string isbn) +std::string add_new_book(std::string isbn) { pid_t pid; - + int exec_status; std::string program_name = "./isbn"; std::string write = "w"; - const char* args[] = {program_name.c_str(), isbn.c_str(), write.c_str()}; + char* args[] = {(char*) program_name.c_str(), (char*) isbn.c_str(), (char*) write.c_str(), NULL}; pid = fork(); - if (0 == pid) { // - // this is the child - } + if (0 == pid) { + execvp(args[0], args); + exit(EXIT_SUCCESS); + } else if (pid < 0) { + perror("Adding book, failed to fork"); + return "Book lookup failed!"; + } else { + wait(&exec_status); - //TODO execvp the args blah blah + if (!WIFEXITED(exec_status)) { + perror("ISBN exited unexpectedly!"); + return "Book lookup failed!"; + } + + if (0 != WEXITSTATUS(exec_status)) { + return "Invalid ISBN submitted!"; + } + + return "Book added successfully!"; + } } diff --git a/api/isbn-interaction.h b/api/isbn-interaction.h index 86ca86c..562ff44 100644 --- a/api/isbn-interaction.h +++ b/api/isbn-interaction.h @@ -17,6 +17,6 @@ std::string book_vec_to_json(std::vector headers, std::vector #include - #include + #include "csv.h" #include "isbn-interaction.h" @@ -23,6 +23,15 @@ int main() return crow::response(get_all_books()); }); + CROW_ROUTE(app, "/add/") + ([](std::string isbn) + { + return crow::response(add_new_book(isbn)); + }); + + + + app.port(18080).run(); } diff --git a/compile.sh b/compile.sh index 9e924df..50baccf 100755 --- a/compile.sh +++ b/compile.sh @@ -3,7 +3,7 @@ make cd bin/ -wget https://github.com/SuperNovaa41/isbn-lookup/releases/download/release/isbn +wget https://github.com/SuperNovaa41/isbn-lookup/releases/download/0.0.2/isbn chmod +x isbn cd ..