JSON RPC
JSON-RPC 2.0 library for C++
utils.cpp
Go to the documentation of this file.
1#include "utils.h"
2#include "exception.h"
3
4/**
5 * @file
6 * @brief Implemenmtation of utility functions for JSON RPC handling.
7 * @internal
8 */
9
10namespace wwa::json_rpc {
11
12bool is_valid_request_id(const nlohmann::json& id)
13{
14 return id.is_string() || id.is_number() || id.is_null() || id.is_discarded();
15}
16
17nlohmann::json get_request_id(const nlohmann::json& request)
18{
19 auto id = request.contains("id") ? request["id"] : nlohmann::json(nullptr);
20 return is_valid_request_id(id) ? id : nlohmann::json(nullptr);
21}
22
23std::string serialize_repsonse(const nlohmann::json& response)
24{
25 return response.is_discarded() ? std::string{} : response.dump();
26}
27
28bool is_error_response(const nlohmann::json& response)
29{
30 return response.is_object() && response.contains("error") && response["error"].is_object();
31}
32
33int get_error_code(const nlohmann::json& response)
34{
35 return response.at("error").value("code", 0);
36}
37
38std::string get_error_message(const nlohmann::json& response)
39{
40 return response.at("error").value("message", "");
41}
42
43nlohmann::json generate_error_response(const exception& e, const nlohmann::json& id)
44{
45 // clang-format off
46 return {
47 {"jsonrpc", "2.0"},
48 {"error", e.to_json()},
49 {"id", id}
50 };
51 // clang-format on
52}
53
54} // namespace wwa::json_rpc
JSON RPC Exception class.
Definition exception.h:86
WWA_JSONRPC_EXPORT std::string serialize_repsonse(const nlohmann::json &response)
Serializes the JSON RPC response to a string.
Definition utils.cpp:23
WWA_JSONRPC_EXPORT std::string get_error_message(const nlohmann::json &response)
Gets the error message from an error response.
Definition utils.cpp:38
WWA_JSONRPC_EXPORT bool is_error_response(const nlohmann::json &response)
Checks whether response is an error response.
Definition utils.cpp:28
WWA_JSONRPC_EXPORT bool is_valid_request_id(const nlohmann::json &id)
Checks if the provided JSON value is a valid JSON RPC request ID.
Definition utils.cpp:12
WWA_JSONRPC_EXPORT nlohmann::json generate_error_response(const exception &e, const nlohmann::json &id=nlohmann::json::value_t::null)
Generates an error response.
Definition utils.cpp:43
WWA_JSONRPC_EXPORT nlohmann::json get_request_id(const nlohmann::json &request)
Get the request id object.
Definition utils.cpp:17
WWA_JSONRPC_EXPORT int get_error_code(const nlohmann::json &response)
Gets the error code from an error response.
Definition utils.cpp:33