virthttp  0.0
libvirt http interface
solver.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <string_view>
3 #include <boost/utility/string_view.hpp> // C++2a this include goes away long before using modules
4 #include <gsl/gsl>
5 #include "handlers/domain.hpp"
7 #include "urlparser.hpp"
8 
9 using namespace std::literals;
10 
20 template <class TPOUH, class KeysT, class FcnsT, class ListFcn> class Resolver {
21  std::string_view type;
22  KeysT skeys;
23  FcnsT sfcns;
24  ListFcn list_fcn;
25 
26  public:
27  using O = typename TPOUH::First;
28  using UH = typename TPOUH::Second;
29 
30  private:
31  [[nodiscard]] constexpr std::pair<int, std::string_view> getSearchKey(const TargetParser& target) const noexcept {
32  const auto& path_parts = target.getPathParts();
33  if (path_parts.size() < 3)
34  return {-1, ""};
35  if (path_parts.size() < 4)
36  return {std::numeric_limits<int>::min(), std::string_view{}};
37 
38  const auto path_part = path_parts[2];
39  const auto it = cexpr::find(skeys.begin(), skeys.end(), path_part);
40  if (it == skeys.end())
41  return {std::numeric_limits<int>::min(), std::string_view{}};
42 
43  const auto idx = std::distance(skeys.begin(), it);
44  return {idx, path_parts[3]};
45  }
46 
47  public:
48  constexpr Resolver(TPOUH, std::string_view type, KeysT skeys, FcnsT sfcns, ListFcn list_fcn) noexcept
49  : type(type), skeys(skeys), sfcns(sfcns), list_fcn(list_fcn) {}
50 
51  auto operator()(HandlerContext& hc) const -> std::vector<O> {
52  const TargetParser& target = hc.target;
53  using Ret = std::vector<O>;
54  auto error = [&](auto... args) { return hc.json_res.error(args...); };
55 
56  const auto [idx, search_value] = getSearchKey(target);
57  if (search_value.data() == nullptr)
58  return error(101), Ret{}; // Basically happens when: 1. there's an unknown key 2. there's a known key but no value
59 
60  Ret ret;
61  if (idx >= 0) {
62  if (auto dom_res = sfcns[idx](hc, search_value); dom_res)
63  ret.emplace_back(std::move(dom_res));
64  else
65  error(100);
66  } else {
67  const auto flags_opt = UH{hc}.search_all_flags(target);
68  if (!flags_opt)
69  return error(102), Ret{}; // Happens when flags cause failure
70  const auto flags = *flags_opt;
71  ret = list_fcn(hc, flags);
72  }
73  return ret;
74  }
75 };
constexpr Resolver(TPOUH, std::string_view type, KeysT skeys, FcnsT sfcns, ListFcn list_fcn) noexcept
Definition: solver.hpp:48
auto operator()(HandlerContext &hc) const -> std::vector< O >
Definition: solver.hpp:51
typename TPOUH::First O
Definition: solver.hpp:27
Definition: hdl_ctx.hpp:11
constexpr InputIt find(InputIt first, InputIt last, const T &value)
Definition: cexpr_algs.hpp:4
Definition: urlparser.hpp:36
typename TPOUH::Second UH
Definition: solver.hpp:28
Definition: solver.hpp:20