userver: userver/chaotic/object.hpp Source File
Loading...
Searching...
No Matches
object.hpp
1#pragma once
2
3#include <string>
4#include <unordered_map>
5
6#include <fmt/format.h>
7
8#include <userver/formats/common/items.hpp>
9#include <userver/formats/json/value_builder.hpp>
10#include <userver/utils/trivial_map.hpp>
11
12USERVER_NAMESPACE_BEGIN
13
14namespace chaotic {
15
16template <typename BuilderFunc, typename Value>
17Value ExtractAdditionalPropertiesTrue(
18 const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
19 typename Value::Builder builder(formats::common::Type::kObject);
20
21 for (const auto& [name, value] : formats::common::Items(json)) {
22 if (names_to_exclude.Contains(name)) continue;
23
24 builder[name] = value;
25 }
26 return builder.ExtractValue();
27}
28
29template <typename BuilderFunc, typename Value>
30void ValidateNoAdditionalProperties(
31 const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
32 for (const auto& [name, value] : formats::common::Items(json)) {
33 if (names_to_exclude.Contains(name)) continue;
34
35 throw std::runtime_error(fmt::format("Unknown property '{}'", name));
36 }
37}
38
39template <typename T, template <typename...> typename Map, typename Value,
40 typename BuilderFunc>
41Map<std::string, formats::common::ParseType<Value, T>>
42ExtractAdditionalProperties(
43 const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
44 Map<std::string, formats::common::ParseType<Value, T>> map;
45
46 for (const auto& [name, value] : formats::common::Items(json)) {
47 if (names_to_exclude.Contains(name)) continue;
48
49 map.emplace(name, value.template As<T>());
50 }
51 return map;
52}
53
54} // namespace chaotic
55
56USERVER_NAMESPACE_END