blob: 699fb2a08fc3e23bd722d3753f65dbdd601fe5fd [file] [log] [blame]
Ed Tanous08bbe112023-04-06 13:10:02 -07001#pragma once
2#include "baserule.hpp"
3#include "ruleparametertraits.hpp"
4#include "websocket.hpp"
5
6#include <boost/beast/http/verb.hpp>
7
8#include <functional>
9#include <limits>
10#include <string>
11#include <type_traits>
12
13namespace crow
14{
15namespace detail
16{
Ed Tanous08bbe112023-04-06 13:10:02 -070017
18template <typename Func, typename... ArgsWrapped>
19struct Wrapped
Ed Tanous1017ef82023-06-27 09:52:58 -070020{};
21
22template <typename Func, typename... ArgsWrapped>
23struct Wrapped<Func, std::tuple<ArgsWrapped...>>
Ed Tanous08bbe112023-04-06 13:10:02 -070024{
Ed Tanous1017ef82023-06-27 09:52:58 -070025 explicit Wrapped(Func f) : handler(std::move(f)) {}
Ed Tanous08bbe112023-04-06 13:10:02 -070026
Ed Tanouscfe3bc02023-06-26 12:47:24 -070027 std::function<void(ArgsWrapped...)> handler;
Ed Tanous08bbe112023-04-06 13:10:02 -070028
29 void operator()(const Request& req,
30 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
31 const std::vector<std::string>& params)
32 {
Ed Tanouscfe3bc02023-06-26 12:47:24 -070033 if constexpr (sizeof...(ArgsWrapped) == 2)
34 {
35 handler(req, asyncResp);
36 }
37 else if constexpr (sizeof...(ArgsWrapped) == 3)
38 {
39 handler(req, asyncResp, params[0]);
40 }
41 else if constexpr (sizeof...(ArgsWrapped) == 4)
42 {
43 handler(req, asyncResp, params[0], params[1]);
44 }
45 else if constexpr (sizeof...(ArgsWrapped) == 5)
46 {
47 handler(req, asyncResp, params[0], params[1], params[2]);
48 }
49 else if constexpr (sizeof...(ArgsWrapped) == 6)
50 {
51 handler(req, asyncResp, params[0], params[1], params[2], params[3]);
52 }
53 else if constexpr (sizeof...(ArgsWrapped) == 7)
54 {
55 handler(req, asyncResp, params[0], params[1], params[2], params[3],
56 params[4]);
57 }
Ed Tanous08bbe112023-04-06 13:10:02 -070058 }
59};
Ed Tanous08bbe112023-04-06 13:10:02 -070060} // namespace detail
61
62class DynamicRule : public BaseRule, public RuleParameterTraits<DynamicRule>
63{
64 public:
65 explicit DynamicRule(const std::string& ruleIn) : BaseRule(ruleIn) {}
66
67 void validate() override
68 {
69 if (!erasedHandler)
70 {
71 throw std::runtime_error("no handler for url " + rule);
72 }
73 }
74
75 void handle(const Request& req,
76 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
77 const std::vector<std::string>& params) override
78 {
79 erasedHandler(req, asyncResp, params);
80 }
81
82 template <typename Func>
83 void operator()(Func f)
84 {
85 using boost::callable_traits::args_t;
Ed Tanous1017ef82023-06-27 09:52:58 -070086 erasedHandler = detail::Wrapped<Func, args_t<Func>>(std::move(f));
Ed Tanous08bbe112023-04-06 13:10:02 -070087 }
88
89 private:
90 std::function<void(const Request&,
91 const std::shared_ptr<bmcweb::AsyncResp>&,
92 const std::vector<std::string>&)>
93 erasedHandler;
94};
95
96} // namespace crow