client_util.hpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #pragma once
  2. #include <tuple>
  3. #if __cplusplus > 201402L
  4. #include <string_view>
  5. using string_view = std::string_view;
  6. #else
  7. #ifdef ASIO_STANDALONE
  8. #include "string_view.hpp"
  9. using namespace nonstd;
  10. #else
  11. #include <boost/utility/string_view.hpp>
  12. using string_view = boost::string_view;
  13. #endif
  14. #endif
  15. #include "codec.h"
  16. namespace rest_rpc {
  17. inline bool has_error(string_view result) {
  18. if (result.empty()) {
  19. return true;
  20. }
  21. rpc_service::msgpack_codec codec;
  22. auto tp = codec.unpack<std::tuple<int>>(result.data(), result.size());
  23. return std::get<0>(tp) != 0;
  24. }
  25. template<typename T>
  26. inline T get_result(string_view result) {
  27. rpc_service::msgpack_codec codec;
  28. auto tp = codec.unpack<std::tuple<int, T>>(result.data(), result.size());
  29. return std::get<1>(tp);
  30. }
  31. inline std::string get_error_msg(string_view result) {
  32. rpc_service::msgpack_codec codec;
  33. auto tp = codec.unpack<std::tuple<int, std::string>>(result.data(), result.size());
  34. return std::get<1>(tp);
  35. }
  36. template<typename T>
  37. inline T as(string_view result) {
  38. if (has_error(result)) {
  39. throw std::logic_error(get_error_msg(result));
  40. }
  41. return get_result<T>(result);
  42. }
  43. }