userver: userver/chaotic/with_type.hpp Source File
Loading...
Searching...
No Matches
with_type.hpp
1#pragma once
2
3#include <userver/formats/json/value.hpp>
4#include <userver/formats/parse/to.hpp>
5
6#include <userver/chaotic/convert.hpp>
7#include <userver/chaotic/convert/to.hpp>
8#include <userver/chaotic/exception.hpp>
9
10USERVER_NAMESPACE_BEGIN
11
12namespace chaotic {
13
14template <typename RawType, typename UserType>
15struct WithType final {
16 const UserType& value;
17};
18
19template <typename Value, typename RawType, typename UserType>
20UserType Parse(const Value& value, formats::parse::To<WithType<RawType, UserType>>) {
21 auto result = value.template As<RawType>();
22 try {
23 return Convert(result, convert::To<UserType>{});
24 } catch (const std::exception& e) {
25 chaotic::ThrowForValue(e.what(), value);
26 }
27}
28
29template <typename Value, typename RawType, typename UserType>
30Value Serialize(const WithType<RawType, UserType>& ps, formats::serialize::To<Value>) {
31 return typename Value::Builder{RawType{Convert(ps.value, convert::To<std::decay_t<decltype(RawType::value)>>())}}
32 .ExtractValue();
33}
34
35} // namespace chaotic
36
37USERVER_NAMESPACE_END