You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.6 KiB
56 lines
1.6 KiB
#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
|