diff --git a/Cargo.lock b/Cargo.lock index fa35351..5389c16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -394,6 +394,7 @@ version = "0.1.0" dependencies = [ "chrono", "serde", + "serde_json", "ts-rs", "uuid", ] diff --git a/example/Cargo.toml b/example/Cargo.toml index 78487c8..f110cfa 100644 --- a/example/Cargo.toml +++ b/example/Cargo.toml @@ -7,5 +7,6 @@ edition = "2021" [dependencies] ts-rs = { path = "../ts-rs", features = ["serde-compat", "uuid-impl"] } serde = { version = "1", features = ["derive", "rc"] } +serde_json = { version = "1" } chrono = { version = "0.4", features = ["serde"] } uuid = { version = "1.1.2", features = ["v4", "serde"] } diff --git a/example/src/lib.rs b/example/src/lib.rs index acae346..c5263dc 100644 --- a/example/src/lib.rs +++ b/example/src/lib.rs @@ -28,6 +28,7 @@ enum Gender { #[derive(Serialize, TS)] #[ts(export)] +#[ts_constant(default, export_to = "constants.ts")] struct User { user_id: i32, first_name: String, @@ -41,6 +42,22 @@ struct User { created_at: NaiveDateTime, } +#[allow(deprecated)] +impl Default for User { + fn default() -> Self { + Self { + user_id: 101, + first_name: "John".to_string(), + last_name: "Doe".to_string(), + role: Role::User, + family: Vec::new(), + gender: Gender::Male, + token: Uuid::default(), + created_at: NaiveDateTime::from_timestamp(0, 0), + } + } +} + #[derive(Serialize, TS)] #[serde(tag = "type", rename_all = "snake_case")] #[ts(export)] @@ -98,9 +115,10 @@ enum InlineComplexEnum { U(Box), } -#[derive(Serialize, TS)] +#[derive(Serialize, TS, Default)] #[serde(rename_all = "camelCase")] #[ts(export)] +#[ts_constant(default, export_to = "constants.ts")] struct ComplexStruct { #[serde(default)] pub string_tree: Option>>, diff --git a/macros/src/attr/constant.rs b/macros/src/attr/constant.rs index 049fd79..8ddf9f1 100644 --- a/macros/src/attr/constant.rs +++ b/macros/src/attr/constant.rs @@ -9,6 +9,7 @@ pub struct ConstantAttr { pub docs: Vec, pub rename: Option, pub array: bool, + pub default: bool, } impl Attr for ConstantAttr { @@ -21,6 +22,7 @@ impl Attr for ConstantAttr { docs: other.docs, rename: self.rename.or(other.rename), array: self.array || other.array, + default: self.default || other.default, } } @@ -43,5 +45,6 @@ impl_parse! { "export_to" => out.export_to = Some(parse_assign_expr(input)?), "rename" => out.rename = Some(parse_assign_expr(input)?), "array" => out.array = true, + "default" => out.default = true, } } diff --git a/macros/src/attr/struct.rs b/macros/src/attr/struct.rs index f9f0f27..e586368 100644 --- a/macros/src/attr/struct.rs +++ b/macros/src/attr/struct.rs @@ -23,6 +23,7 @@ pub struct StructAttr { pub export: bool, pub tag: Option, pub docs: Vec, + pub default: bool, pub concrete: HashMap, pub bound: Option>, pub optional_fields: Optional, @@ -85,6 +86,7 @@ impl Attr for StructAttr { export: self.export || other.export, tag: self.tag.or(other.tag), docs: other.docs, + default: self.default || other.default, concrete: self.concrete.into_iter().chain(other.concrete).collect(), bound: match (self.bound, other.bound) { (Some(a), Some(b)) => Some(a.into_iter().chain(b).collect()), diff --git a/macros/src/lib.rs b/macros/src/lib.rs index 8e218e5..782a0bd 100644 --- a/macros/src/lib.rs +++ b/macros/src/lib.rs @@ -518,6 +518,12 @@ fn run_constant(input: Item, attrs: ConstantAttr) -> Result { let type_name = Ident::new(&ident_str, c.ident.span()); (constant::constant_def(&c, attrs)?, type_name, c.generics.clone()) }, + Item::Struct(s) => { + let ident_str = Inflection::Lower.apply(&s.ident.to_string()); + let ident_str = format!("TsConstant{}", Inflection::Pascal.apply(&ident_str)); + let type_name = Ident::new(&ident_str, s.ident.span()); + (constant::constant_def_struct(&s, attrs)?, type_name, s.generics.clone()) + }, _ => syn_err!(input.span(); "expected constant"), }; let out_struct = quote! { diff --git a/macros/src/types/constant.rs b/macros/src/types/constant.rs index 5c98127..f394bd2 100644 --- a/macros/src/types/constant.rs +++ b/macros/src/types/constant.rs @@ -1,5 +1,5 @@ use quote::quote; -use syn::{ext::IdentExt, spanned::Spanned, Error, Expr, ItemConst, Lit, Result}; +use syn::{ext::IdentExt, spanned::Spanned, Error, Expr, Ident, ItemConst, ItemStruct, Lit, Result}; use crate::{attr::{Attr, ConstantAttr, ContainerAttr}, utils::make_string_literal, Dependencies, DerivedTS}; @@ -11,6 +11,53 @@ pub(crate) fn constant_def(s: &ItemConst, attr: ConstantAttr) -> Result Result { + let ident_name = match &attr.rename { + Some(rename) => { + if let Expr::Lit(lit_str) = rename { + if let Lit::Str(lit_str) = &lit_str.lit { + Ident::new(&lit_str.value(), lit_str.span()) + } else { + return Err(Error::new(rename.span(), "expected string literal")); + } + } else { + return Err(Error::new(rename.span(), "expected string literal")); + } + }, + _ => strct.ident.unraw(), + }; + let ts_name = match &attr.rename { + Some(rename) => rename.clone(), + _ => { + let mut name = strct.ident.unraw().to_string(); + name.insert_str(0, "Default"); + make_string_literal(&name, strct.ident.span()) + }, + }; + attr.assert_validity(&())?; + let crate_rename = attr.crate_rename(); + + let inline = quote! { + serde_json::to_string_pretty(&#ident_name::default()) + .expect(&format!("Failed to serialize {} constant for ts_constant(default)", stringify!(#ident_name))) + }; + + Ok(DerivedTS { + crate_rename: crate_rename.clone(), + inline: quote!(#inline), + inline_flattened: None, + docs: attr.docs.clone(), + dependencies: Dependencies::new(crate_rename), + export: attr.export_to.is_some(), + export_to: attr.export_to.clone(), + ts_name, + concrete: Default::default(), + bound: None, + is_ts_enum: false, + is_constant: true, + }) +} + fn type_def(attr: &ConstantAttr, ts_name: Expr, value: &Expr) -> Result { attr.assert_validity(&())?; let crate_rename = attr.crate_rename();