JODA  0.13.1 (59b41972)
JSON On-Demand Analysis
JodaServer.h
Go to the documentation of this file.
1 //
2 // Created by Nico on 22/08/2019.
3 //
4 
5 #ifndef JODA_JODASERVER_H
6 #define JODA_JODASERVER_H
7 
8 #include <glog/logging.h>
9 #include <httplib.h>
10 #include <joda/misc/RJFwd.h>
11 #include <joda/misc/Timer.h>
12 
13 namespace joda::network {
14 
18 class JodaAPIException : public std::runtime_error {
19  public:
24  explicit JodaAPIException(const std::string &what)
25  : std::runtime_error("API Error: " + what){};
26 };
27 
32 class JodaServer {
33  public:
38  static constexpr auto prefix = "/api";
39 
46  bool start(const std::string &addr, int port);
47 
52  void stop();
53 
61  static void handleError(JodaAPIException &e, httplib::Response &res);
62 
70  static void sendResponse(RJDocument &doc, httplib::Response &res);
71 
79  template <class F>
80  static void logExecutionTime(const std::string &endpoint, F f) {
81  Timer timer;
82  f();
83  timer.stop();
84  LOG(INFO) << endpoint << " execution took " << timer.toHumanDuration();
85  }
86 
87  private:
88  httplib::Server server;
89 
90  static std::string printParameters(const httplib::Params &p);
91 
92  static void favicon(const httplib::Request &req, httplib::Response &res);
93 };
94 
99  public:
100  explicit JodaMissingParameterException(const std::string &param)
101  : JodaAPIException("Missing '" + param + "' parameter") {}
102 };
103 
108  public:
109  JodaInvalidParameterException(const std::string &param,
110  const std::string &what)
111  : JodaAPIException("Invalid '" + param + "' parameter: " + what) {}
112 };
113 
114 } // namespace joda::network
115 
116 #endif // JODA_JODASERVER_H
rapidjson::GenericDocument< RJChar, RJMemoryPoolAlloc, RJBaseAlloc > RJDocument
Definition: RJFwd.h:28
Definition: Timer.h:17
void stop()
Definition: Timer.cpp:22
std::string toHumanDuration() const
Definition: Timer.cpp:60
Definition: JodaServer.h:18
JodaAPIException(const std::string &what)
Definition: JodaServer.h:24
JodaInvalidParameterException(const std::string &param, const std::string &what)
Definition: JodaServer.h:109
JodaMissingParameterException(const std::string &param)
Definition: JodaServer.h:100
Definition: JodaServer.h:32
static void sendResponse(RJDocument &doc, httplib::Response &res)
Definition: JodaServer.cpp:56
static void logExecutionTime(const std::string &endpoint, F f)
Definition: JodaServer.h:80
void stop()
Definition: JodaServer.cpp:65
static constexpr auto prefix
Definition: JodaServer.h:38
bool start(const std::string &addr, int port)
Definition: JodaServer.cpp:16
static void handleError(JodaAPIException &e, httplib::Response &res)
Definition: JodaServer.cpp:47
Definition: JodaClient.h:12