Make sure that no field is required when we use rfl::DefaultIfMissing; #376 (#385)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-03-16 00:06:27 +08:00
committed by GitHub
parent 8027c21e8a
commit 241112f98c
3 changed files with 123 additions and 39 deletions
+6 -5
View File
@@ -34,15 +34,16 @@ struct TypeHelper<rfl::Variant<Ts...>> {
}; };
std::string to_schema_internal_schema( std::string to_schema_internal_schema(
const parsing::schema::Definition& internal_schema, const parsing::schema::Definition& internal_schema, const yyjson_write_flag,
const yyjson_write_flag); const bool _no_required);
/// Returns the JSON schema for a class. /// Returns the JSON schema for a class.
template <class T, class... Ps> template <class T, class... Ps>
std::string to_schema(const yyjson_write_flag _flag = 0) { std::string to_schema(const yyjson_write_flag _flag = 0) {
const auto internal_schema = using P = Processors<Ps...>;
parsing::schema::make<Reader, Writer, T, Processors<Ps...>>(); const auto internal_schema = parsing::schema::make<Reader, Writer, T, P>();
return to_schema_internal_schema(internal_schema, _flag); return to_schema_internal_schema(internal_schema, _flag,
P::default_if_missing_);
} }
} // namespace rfl::json } // namespace rfl::json
+42 -34
View File
@@ -28,7 +28,8 @@ SOFTWARE.
namespace rfl::json { namespace rfl::json {
schema::Type type_to_json_schema_type(const parsing::schema::Type& _type); schema::Type type_to_json_schema_type(const parsing::schema::Type& _type,
const bool _no_required);
bool is_optional(const parsing::schema::Type& _t) { bool is_optional(const parsing::schema::Type& _t) {
const auto handle = [](const auto& _v) -> bool { const auto handle = [](const auto& _v) -> bool {
@@ -57,28 +58,29 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) {
schema::Type handle_validation_type( schema::Type handle_validation_type(
const parsing::schema::Type& _type, const parsing::schema::Type& _type,
const parsing::schema::ValidationType& _validation_type) { const parsing::schema::ValidationType& _validation_type,
const bool _no_required) {
auto handle_variant = [&](const auto& _v) -> schema::Type { auto handle_variant = [&](const auto& _v) -> schema::Type {
using T = std::remove_cvref_t<decltype(_v)>; using T = std::remove_cvref_t<decltype(_v)>;
using ValidationType = parsing::schema::ValidationType; using ValidationType = parsing::schema::ValidationType;
if constexpr (std::is_same<T, ValidationType::AllOf>()) { if constexpr (std::is_same<T, ValidationType::AllOf>()) {
auto all_of = std::vector<schema::Type>(); auto all_of = std::vector<schema::Type>();
for (const auto& t : _v.types_) { for (const auto& t : _v.types_) {
all_of.emplace_back(handle_validation_type(_type, t)); all_of.emplace_back(handle_validation_type(_type, t, _no_required));
} }
return schema::Type{.value = schema::Type::AllOf{.allOf = all_of}}; return schema::Type{.value = schema::Type::AllOf{.allOf = all_of}};
} else if constexpr (std::is_same<T, ValidationType::AnyOf>()) { } else if constexpr (std::is_same<T, ValidationType::AnyOf>()) {
auto any_of = std::vector<schema::Type>(); auto any_of = std::vector<schema::Type>();
for (const auto& t : _v.types_) { for (const auto& t : _v.types_) {
any_of.emplace_back(handle_validation_type(_type, t)); any_of.emplace_back(handle_validation_type(_type, t, _no_required));
} }
return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}}; return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}};
} else if constexpr (std::is_same<T, ValidationType::OneOf>()) { } else if constexpr (std::is_same<T, ValidationType::OneOf>()) {
auto one_of = std::vector<schema::Type>(); auto one_of = std::vector<schema::Type>();
for (const auto& t : _v.types_) { for (const auto& t : _v.types_) {
one_of.emplace_back(handle_validation_type(_type, t)); one_of.emplace_back(handle_validation_type(_type, t, _no_required));
} }
return schema::Type{.value = schema::Type::OneOf{.oneOf = one_of}}; return schema::Type{.value = schema::Type::OneOf{.oneOf = one_of}};
@@ -86,7 +88,7 @@ schema::Type handle_validation_type(
return schema::Type{.value = schema::Type::Regex{.pattern = _v.pattern_}}; return schema::Type{.value = schema::Type::Regex{.pattern = _v.pattern_}};
} else if constexpr (std::is_same<T, ValidationType::Size>()) { } else if constexpr (std::is_same<T, ValidationType::Size>()) {
auto t = type_to_json_schema_type(_type); auto t = type_to_json_schema_type(_type, _no_required);
const auto to_size = [](const auto _v) { const auto to_size = [](const auto _v) {
return static_cast<size_t>(_v); return static_cast<size_t>(_v);
}; };
@@ -115,7 +117,8 @@ schema::Type handle_validation_type(
v.types_.push_back(ValidationType{ValidationType::Size{ v.types_.push_back(ValidationType{ValidationType::Size{
.size_limit_ = rfl::Ref<ValidationType>::make(limiter)}}); .size_limit_ = rfl::Ref<ValidationType>::make(limiter)}});
} }
return handle_validation_type(_type, ValidationType{.variant_ = v}); return handle_validation_type(_type, ValidationType{.variant_ = v},
_no_required);
} }
} }
return t; return t;
@@ -173,8 +176,9 @@ schema::Type handle_validation_type(
return rfl::visit(handle_variant, _validation_type.variant_); return rfl::visit(handle_variant, _validation_type.variant_);
} }
schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { schema::Type type_to_json_schema_type(const parsing::schema::Type& _type,
auto handle_variant = [](const auto& _t) -> schema::Type { const bool _no_required) {
auto handle_variant = [&](const auto& _t) -> schema::Type {
using T = std::remove_cvref_t<decltype(_t)>; using T = std::remove_cvref_t<decltype(_t)>;
using Type = parsing::schema::Type; using Type = parsing::schema::Type;
if constexpr (std::is_same<T, Type::Boolean>()) { if constexpr (std::is_same<T, Type::Boolean>()) {
@@ -198,12 +202,12 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
} else if constexpr (std::is_same<T, Type::AnyOf>()) { } else if constexpr (std::is_same<T, Type::AnyOf>()) {
auto any_of = std::vector<schema::Type>(); auto any_of = std::vector<schema::Type>();
for (const auto& t : _t.types_) { for (const auto& t : _t.types_) {
any_of.emplace_back(type_to_json_schema_type(t)); any_of.emplace_back(type_to_json_schema_type(t, _no_required));
} }
return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}}; return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}};
} else if constexpr (std::is_same<T, Type::Description>()) { } else if constexpr (std::is_same<T, Type::Description>()) {
auto res = type_to_json_schema_type(*_t.type_); auto res = type_to_json_schema_type(*_t.type_, _no_required);
const auto update_prediction = [&](auto _v) -> schema::Type { const auto update_prediction = [&](auto _v) -> schema::Type {
_v.description = _t.description_; _v.description = _t.description_;
return schema::Type{_v}; return schema::Type{_v};
@@ -211,11 +215,12 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
return rfl::visit(update_prediction, res.value); return rfl::visit(update_prediction, res.value);
} else if constexpr (std::is_same<T, Type::FixedSizeTypedArray>()) { } else if constexpr (std::is_same<T, Type::FixedSizeTypedArray>()) {
return schema::Type{.value = schema::Type::FixedSizeTypedArray{ return schema::Type{
.items = Ref<schema::Type>::make( .value = schema::Type::FixedSizeTypedArray{
type_to_json_schema_type(*_t.type_)), .items = Ref<schema::Type>::make(
.minItems = _t.size_, type_to_json_schema_type(*_t.type_, _no_required)),
.maxItems = _t.size_}}; .minItems = _t.size_,
.maxItems = _t.size_}};
} else if constexpr (std::is_same<T, Type::Literal>()) { } else if constexpr (std::is_same<T, Type::Literal>()) {
return schema::Type{.value = return schema::Type{.value =
@@ -225,15 +230,15 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
auto properties = rfl::Object<schema::Type>(); auto properties = rfl::Object<schema::Type>();
auto required = std::vector<std::string>(); auto required = std::vector<std::string>();
for (const auto& [k, v] : _t.types_) { for (const auto& [k, v] : _t.types_) {
properties[k] = type_to_json_schema_type(v); properties[k] = type_to_json_schema_type(v, _no_required);
if (!is_optional(v)) { if (!is_optional(v) && !_no_required) {
required.push_back(k); required.push_back(k);
} }
} }
auto additional_properties = auto additional_properties =
_t.additional_properties_ _t.additional_properties_
? std::make_shared<schema::Type>( ? std::make_shared<schema::Type>(type_to_json_schema_type(
type_to_json_schema_type(*_t.additional_properties_)) *_t.additional_properties_, _no_required))
: std::shared_ptr<schema::Type>(); : std::shared_ptr<schema::Type>();
return schema::Type{.value = schema::Type::Object{ return schema::Type{.value = schema::Type::Object{
.properties = properties, .properties = properties,
@@ -241,33 +246,36 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
.additionalProperties = additional_properties}}; .additionalProperties = additional_properties}};
} else if constexpr (std::is_same<T, Type::Optional>()) { } else if constexpr (std::is_same<T, Type::Optional>()) {
return schema::Type{.value = schema::Type::AnyOf{ return schema::Type{
.anyOf = {type_to_json_schema_type(*_t.type_), .value = schema::Type::AnyOf{
schema::Type{schema::Type::Null{}}}}}; .anyOf = {type_to_json_schema_type(*_t.type_, _no_required),
schema::Type{schema::Type::Null{}}}}};
} else if constexpr (std::is_same<T, Type::Reference>()) { } else if constexpr (std::is_same<T, Type::Reference>()) {
return schema::Type{ return schema::Type{
.value = schema::Type::Reference{.ref = "#/definitions/" + _t.name_}}; .value = schema::Type::Reference{.ref = "#/definitions/" + _t.name_}};
} else if constexpr (std::is_same<T, Type::StringMap>()) { } else if constexpr (std::is_same<T, Type::StringMap>()) {
return schema::Type{.value = schema::Type::StringMap{ return schema::Type{
.additionalProperties = Ref<schema::Type>::make( .value = schema::Type::StringMap{
type_to_json_schema_type(*_t.value_type_))}}; .additionalProperties = Ref<schema::Type>::make(
type_to_json_schema_type(*_t.value_type_, _no_required))}};
} else if constexpr (std::is_same<T, Type::Tuple>()) { } else if constexpr (std::is_same<T, Type::Tuple>()) {
auto items = std::vector<schema::Type>(); auto items = std::vector<schema::Type>();
for (const auto& t : _t.types_) { for (const auto& t : _t.types_) {
items.emplace_back(type_to_json_schema_type(t)); items.emplace_back(type_to_json_schema_type(t, _no_required));
} }
return schema::Type{.value = schema::Type::Tuple{.prefixItems = items}}; return schema::Type{.value = schema::Type::Tuple{.prefixItems = items}};
} else if constexpr (std::is_same<T, Type::TypedArray>()) { } else if constexpr (std::is_same<T, Type::TypedArray>()) {
return schema::Type{.value = schema::Type::TypedArray{ return schema::Type{
.items = Ref<schema::Type>::make( .value = schema::Type::TypedArray{
type_to_json_schema_type(*_t.type_))}}; .items = Ref<schema::Type>::make(
type_to_json_schema_type(*_t.type_, _no_required))}};
} else if constexpr (std::is_same<T, Type::Validated>()) { } else if constexpr (std::is_same<T, Type::Validated>()) {
return handle_validation_type(*_t.type_, _t.validation_); return handle_validation_type(*_t.type_, _t.validation_, _no_required);
} else { } else {
static_assert(rfl::always_false_v<T>, "Not all cases were covered."); static_assert(rfl::always_false_v<T>, "Not all cases were covered.");
@@ -279,10 +287,10 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) {
std::string to_schema_internal_schema( std::string to_schema_internal_schema(
const parsing::schema::Definition& internal_schema, const parsing::schema::Definition& internal_schema,
const yyjson_write_flag _flag) { const yyjson_write_flag _flag, const bool _no_required) {
auto definitions = std::map<std::string, schema::Type>(); auto definitions = std::map<std::string, schema::Type>();
for (const auto& [k, v] : internal_schema.definitions_) { for (const auto& [k, v] : internal_schema.definitions_) {
definitions[k] = type_to_json_schema_type(v); definitions[k] = type_to_json_schema_type(v, _no_required);
} }
using JSONSchemaType = using JSONSchemaType =
typename TypeHelper<schema::Type::ReflectionType>::JSONSchemaType; typename TypeHelper<schema::Type::ReflectionType>::JSONSchemaType;
@@ -291,7 +299,7 @@ std::string to_schema_internal_schema(
return schema::JSONSchema<U>{.root = std::move(_root), return schema::JSONSchema<U>{.root = std::move(_root),
.definitions = definitions}; .definitions = definitions};
}; };
auto root = type_to_json_schema_type(internal_schema.root_); auto root = type_to_json_schema_type(internal_schema.root_, _no_required);
const auto json_schema = rfl::visit(to_schema, std::move(root.value)); const auto json_schema = rfl::visit(to_schema, std::move(root.value));
return write(json_schema, _flag); return write(json_schema, _flag);
} }
+75
View File
@@ -0,0 +1,75 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <tuple>
#include <variant>
#include <vector>
#include "write_and_read.hpp"
namespace test_json_schema {
enum class Color { red, green, blue };
struct Rectangle {
double width;
double height;
};
struct Square {
double width;
};
struct Circle {
double radius;
};
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
using FieldVariant =
rfl::Variant<rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", Square>, rfl::Field<"circle", Circle>>;
struct WithExtraFields {
std::string f1;
std::string f2;
rfl::ExtraFields<std::string> extra_fields;
};
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
rfl::Description<"Must be a proper email in the form xxx@xxx.xxx.",
rfl::Email>
email;
std::string town = "Springfield";
Color color;
Age age;
float salary;
rfl::Description<
"The person's children. Pass an empty array for no children.",
std::vector<Person>>
children;
std::variant<Color, std::vector<Person>, int> variant;
std::tuple<Color, std::vector<Person>, int> tuple;
rfl::Rename<"taggedUnion",
rfl::TaggedUnion<"shape", Rectangle, Square, Circle>>
tagged_union;
rfl::Rename<"fieldVariant", FieldVariant> field_variant;
rfl::Generic generic;
WithExtraFields with_extra_fields;
};
TEST(json, test_json_schema4) {
const auto json_schema =
rfl::json::to_schema<Person, rfl::DefaultIfMissing>();
std::cout << json_schema << std::endl;
const std::string expected =
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","definitions":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/definitions/rfl__Generic"}},{"type":"array","items":{"$ref":"#/definitions/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":[]}]},"generic":{"$ref":"#/definitions/rfl__Generic"},"with_extra_fields":{"$ref":"#/definitions/test_json_schema__WithExtraFields"}},"required":[]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})";
EXPECT_EQ(json_schema, expected);
}
} // namespace test_json_schema