1
0
mirror of https://github.com/binary-kitchen/doorlockd synced 2024-10-01 18:22:23 +02:00
doorlockd-mirror/doorlockd/lib/response.cpp

70 lines
1.4 KiB
C++
Raw Normal View History

2015-09-25 00:25:26 +02:00
#include <exception>
2015-09-22 21:22:48 +02:00
#include <json/json.h>
#include "response.h"
2015-09-25 00:25:26 +02:00
#include "util.h"
2015-09-22 21:22:48 +02:00
const std::string Response::_codeKey = "code";
const std::string Response::_messageKey = "message";
Response::Response():
code(Fail),
message("General failure")
{
}
Response::Response(Response::Code code, const std::string &what) :
code(code),
message(what)
{
}
2015-09-22 21:22:48 +02:00
Response::operator bool() const
{
return code == Response::Code::Success;
}
std::string Response::toJson() const
{
Json::Value response;
Json::StyledWriter writer;
response[_codeKey] = code;
response[_messageKey] = message;
return writer.write(response);
}
2015-09-25 00:25:26 +02:00
Response Response::fromJson(const Json::Value &root)
2015-09-25 00:25:26 +02:00
{
Response retval;
try {
retval.message = getJsonOrFail<std::string>(root, _messageKey);
2015-09-25 00:25:26 +02:00
const auto code = getJsonOrFail<int>(root, _codeKey);
if (code > Code::RESPONSE_NUM_ITEMS)
throw std::runtime_error("Error code out of range");
2015-09-25 00:25:26 +02:00
retval.code = static_cast<Code>(code);
}
catch (const std::exception &ex) {
throw Response(Response::Code::JsonError, ex.what());
}
2015-09-25 00:25:26 +02:00
return retval;
}
Response Response::fromString(const std::string &json)
{
Json::Reader reader;
Json::Value root;
if (reader.parse(json, root) == false)
throw Response(Response::Code::NotJson,
"No valid JSON");
return fromJson(root);
}