#include "webapi/controllers/StoreController.h" #include "infrastructure/helpers/JsonItem.h" #include "infrastructure/helpers/Jsend.h" namespace nxl::autostore::webapi { using infrastructure::Jsend; using infrastructure::JsonItem; StoreController::StoreController(application::AddItem& addItemUseCase) : addItemUseCase(addItemUseCase) {} void StoreController::registerRoutes(httplib::Server& server) { server.Post("/api/items", [this](const httplib::Request& req, httplib::Response& res) { this->addItem(req, res); }); } void StoreController::addItem(const httplib::Request& req, httplib::Response& res) { try { if (req.body.empty()) { res.status = 400; res.set_content(Jsend::error("Request body is empty", 400), "application/json"); return; } auto item = JsonItem::fromJson(req.body); try { addItemUseCase.execute(std::move(item), [&res](auto item) { res.status = 201; nlohmann::json responseData = nlohmann::json::object(); responseData["id"] = item.id; res.set_content(Jsend::success(responseData), "application/json"); }); } catch (const std::exception& e) { res.status = 500; res.set_content( Jsend::error("Failed to add item: " + std::string(e.what()), res.status), "application/json"); } } catch (const std::exception& e) { res.status = 400; res.set_content(Jsend::error(e.what(), res.status), "application/json"); } } } // namespace nxl::autostore::webapi