diff --git a/doorlockd/src/response.cpp b/doorlockd/src/response.cpp index ab54fe9..e747a93 100644 --- a/doorlockd/src/response.cpp +++ b/doorlockd/src/response.cpp @@ -1,6 +1,9 @@ +#include + #include #include "response.h" +#include "util.h" const std::string Response::_codeKey = "code"; const std::string Response::_messageKey = "message"; @@ -20,3 +23,22 @@ std::string Response::toJson() const return writer.write(response); } + +Response Response::fromJson(const std::string &json) +{ + Json::Reader reader; + Json::Value root; + Response retval; + + if (reader.parse(json, root) == false) + throw std::runtime_error("Error parsing JSON"); + + retval.message = getJsonOrFail(root, _messageKey); + + const auto code = getJsonOrFail(root, _codeKey); + if (code > Code::RESPONSE_NUM_ITEMS) + throw std::runtime_error("Error code out of range"); + retval.code = static_cast(code); + + return retval; +} diff --git a/doorlockd/src/response.h b/doorlockd/src/response.h index 13fd15c..46d1505 100644 --- a/doorlockd/src/response.h +++ b/doorlockd/src/response.h @@ -18,11 +18,9 @@ struct Response UnknownCommand, // Unknown action LDAPInit, // Ldap initialization failed AccessDenied, // Access denied + RESPONSE_NUM_ITEMS } code; - std::string message; - std::string toJson() const; - operator bool() const; Response() : code(Fail), @@ -36,6 +34,12 @@ struct Response { } + static Response fromJson(const std::string &json); + std::string toJson() const; + + // Returns true if code is success + operator bool() const; + private: const static std::string _codeKey;