Skip to content

Commit ff9cc71

Browse files
Made sure the Description and Validated retain optional; fixes #503 (#508)
1 parent 03649d1 commit ff9cc71

File tree

2 files changed

+43
-4
lines changed

2 files changed

+43
-4
lines changed

src/rfl/json/to_schema.cpp

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,18 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type,
3232
const bool _no_required);
3333

3434
bool is_optional(const parsing::schema::Type& _t) {
35-
const auto handle = [](const auto& _v) -> bool {
35+
return _t.variant_.visit([&](const auto& _v) -> bool {
3636
using T = std::remove_cvref_t<decltype(_v)>;
37-
return std::is_same<T, parsing::schema::Type::Optional>();
38-
};
39-
return rfl::visit(handle, _t.variant_);
37+
if constexpr (std::is_same_v<T, parsing::schema::Type::Description>) {
38+
return is_optional(*_v.type_);
39+
40+
} else if constexpr (std::is_same_v<T, parsing::schema::Type::Validated>) {
41+
return is_optional(*_v.type_);
42+
43+
} else {
44+
return std::is_same_v<T, parsing::schema::Type::Optional>;
45+
}
46+
});
4047
}
4148

4249
std::string numeric_type_to_string(const parsing::schema::Type& _type) {

tests/json/test_json_schema5.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <iostream>
2+
#include <optional>
3+
#include <rfl.hpp>
4+
#include <rfl/json.hpp>
5+
#include <string>
6+
#include <tuple>
7+
#include <vector>
8+
9+
#include "write_and_read.hpp"
10+
11+
namespace test_json_schema5 {
12+
13+
using Age = rfl::Validator<std::optional<unsigned int>, rfl::Minimum<0>,
14+
rfl::Maximum<130>>;
15+
16+
struct Person {
17+
rfl::Description<"Given name of this person", std::string> first_name;
18+
rfl::Description<"Optional family name of this person",
19+
std::optional<std::string>>
20+
last_name;
21+
Age age;
22+
};
23+
24+
TEST(json, test_json_schema5) {
25+
const auto json_schema = rfl::json::to_schema<Person>();
26+
27+
const std::string expected =
28+
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema5__Person","definitions":{"test_json_schema5__Person":{"type":"object","properties":{"first_name":{"type":"string","description":"Given name of this person"},"last_name":{"description":"Optional family name of this person","anyOf":[{"type":"string"},{"type":"null"}]},"age":{"allOf":[{"minimum":0,"type":"number"},{"maximum":130,"type":"number"}]}},"required":["first_name"]}}})";
29+
30+
EXPECT_EQ(json_schema, expected);
31+
}
32+
} // namespace test_json_schema5

0 commit comments

Comments
 (0)