Skip to main content

reflectapi_schema/
transforms.rs

1use crate::{Field, TypeReference, Typespace};
2
3/// Unwraps transparent wrappers (e.g. `Arc<T>` → `T`) on the field's type reference.
4pub fn fallback_recursively(field: &mut Field, schema: &Typespace) {
5    field.type_ref.fallback_recursively(schema);
6}
7
8/// Makes a field required in the schema.
9///
10/// - `std::option::Option<T>` → required `T`
11/// - `reflectapi::Option<T>` → required `std::option::Option<T>`
12///   (removes the "undefined" state, keeps nullable)
13/// - Other types → marks the field as required without changing the type
14pub fn make_required(field: &mut Field, _schema: &Typespace) {
15    if field.type_ref.name() == "std::option::Option" {
16        if let Some(inner) = field.type_ref.arguments().next().cloned() {
17            field.type_ref = inner;
18        }
19    } else if field.type_ref.name() == "reflectapi::Option" {
20        let arguments = field.type_ref.arguments().cloned().collect::<Vec<_>>();
21        field.type_ref = TypeReference::new("std::option::Option", arguments);
22    }
23    field.required = true;
24}
25
26/// Makes a field non-nullable in the schema.
27///
28/// - `std::option::Option<T>` → `T` (required unchanged)
29/// - `reflectapi::Option<T>` → `T` (required unchanged)
30///   (removes the "null" state, keeps optionality)
31/// - Other types → no-op (already non-nullable)
32pub fn make_nonnullable(field: &mut Field, _schema: &Typespace) {
33    if field.type_ref.name() == "std::option::Option"
34        || field.type_ref.name() == "reflectapi::Option"
35    {
36        if let Some(inner) = field.type_ref.arguments().next().cloned() {
37            field.type_ref = inner;
38        }
39    }
40}
41
42/// Makes a field both required and non-nullable in the schema.
43///
44/// - `std::option::Option<T>` → required `T`
45/// - `reflectapi::Option<T>` → required `T`
46///   (removes both "undefined" and "null" states)
47/// - Other types → marks the field as required without changing the type
48pub fn make_required_and_nonnullable(field: &mut Field, schema: &Typespace) {
49    make_nonnullable(field, schema);
50    make_required(field, schema);
51}