JSON RPC
JSON-RPC 2.0 library for C++
dispatcher.cpp
Go to the documentation of this file.
1/**
2 * @file
3 * @brief Implementation of the dispatcher class.
4 */
5
6#include "dispatcher.h"
7#include "dispatcher_p.h"
8#include "exception.h"
9
10namespace wwa::json_rpc {
11
13
14dispatcher::~dispatcher() = default;
15
16void dispatcher::add_internal_method(std::string_view method, handler_t&& handler)
17{
18 this->d_ptr->add_handler(std::string(method), std::move(handler));
19}
20
21std::string dispatcher::parse_and_process_request(const std::string& request, const nlohmann::json& extra)
22{
23 nlohmann::json req;
24 try {
25 req = nlohmann::json::parse(request);
26 }
27 catch (const nlohmann::json::exception& e) {
28 this->on_request(extra);
29 const auto json = dispatcher_private::generate_error_response(
30 exception(exception::PARSE_ERROR, e.what()), nlohmann::json(nullptr)
31 );
32
33 this->on_request_processed({}, exception::PARSE_ERROR, extra);
34 return json.dump();
35 }
36
37 return this->process_request(req, extra);
38}
39
40std::string dispatcher::process_request(const nlohmann::json& request, const nlohmann::json& extra)
41{
42 const auto json = this->d_ptr->process_request(request, extra);
43 return json.is_discarded() ? std::string{} : json.dump();
44}
45
47{
48 // Do nothing
49}
50
51void dispatcher::on_method(const std::string&, const nlohmann::json&)
52{
53 // Do nothing
54}
55
56void dispatcher::on_request_processed(const std::string&, int, const nlohmann::json&)
57{
58 // Do nothing
59}
60
61} // namespace wwa::json_rpc
A class that manages JSON RPC method handlers and processes JSON RPC requests.
Definition dispatcher.h:77
virtual void on_request(const nlohmann::json &extra)
Invoked when a request is received.
std::string parse_and_process_request(const std::string &request, const nlohmann::json &extra=nlohmann::json::object())
Parses and processes a JSON RPC request.
std::string process_request(const nlohmann::json &request, const nlohmann::json &extra=nlohmann::json::object())
Processes a JSON RPC request.
virtual void on_request_processed(const std::string &method, int code, const nlohmann::json &extra)
Invoked after the method handler is called.
void add_internal_method(std::string_view method, handler_t &&handler)
Adds a method handler for the specified method.
virtual void on_method(const std::string &method, const nlohmann::json &extra)
Invoked right before the method handler is called.
dispatcher()
Class constructor.
virtual ~dispatcher()
Class destructor.