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(const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
18 typename Value::Builder builder(formats::common::Type::kObject);
19
20 for (const auto& [name, value] : formats::common::Items(json)) {
21 if (names_to_exclude.Contains(name)) continue;
22
23 builder[name] = value;
24 }
25 return builder.ExtractValue();
26}
27
28template <typename BuilderFunc, typename Value>
29void ValidateNoAdditionalProperties(const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
30 for (const auto& [name, value] : formats::common::Items(json)) {
31 if (names_to_exclude.Contains(name)) continue;
32
33 throw std::runtime_error(fmt::format("Unknown property '{}'", name));
34 }
35}
36
37template <typename T, template <typename...> typename Map, typename Value, typename BuilderFunc>
38Map<std::string, formats::common::ParseType<Value, T>>
39ExtractAdditionalProperties(const Value& json, const utils::TrivialSet<BuilderFunc>& names_to_exclude) {
40 Map<std::string, formats::common::ParseType<Value, T>> map;
41
42 for (const auto& [name, value] : formats::common::Items(json)) {
43 if (names_to_exclude.Contains(name)) continue;
44
45 map.emplace(name, value.template As<T>());
46 }
47 return map;
48}
49
50} // namespace chaotic
51
52USERVER_NAMESPACE_END