type_reflect/ts_validation/enum_type/
mod.rs

1use type_reflect_core::EnumType;
2use untagged::emit_untagged_enum_type;
3
4use crate::{ts_validation::validation_namespace, EnumReflectionType};
5
6mod complex;
7use complex::*;
8
9mod case_type;
10
11mod untagged;
12
13pub fn emit_enum_type<T>() -> String
14where
15    T: EnumReflectionType,
16{
17    match T::enum_type() {
18        EnumType::Simple => emit_simple_enum_type::<T>(),
19        EnumType::Complex {
20            case_key,
21            content_key,
22        } => emit_complex_enum_type::<T>(&case_key, &content_key),
23        EnumType::Untagged => emit_untagged_enum_type::<T>(),
24    }
25}
26
27fn emit_simple_enum_type<T>() -> String
28where
29    T: EnumReflectionType,
30{
31    let validation_impl = format!(
32        r#"
33if(Object.values({name}).includes(input as {name})) {{
34    return input as {name};
35}}
36throw new Error(`Error parsing {name}: value does not conform: ${{JSON.stringify(input)}}`)
37"#,
38        name = T::name(),
39    );
40    validation_namespace(T::name(), validation_impl.as_str())
41}