Skip to content

Commit

Permalink
Merge pull request #69 from oscartbeaumont/67-apply-optional-if-serde…
Browse files Browse the repository at this point in the history
…default-detected

serde optional
  • Loading branch information
oscartbeaumont authored Apr 28, 2023
2 parents 527a4aa + 99aa9c9 commit 1e11212
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 27 deletions.
1 change: 1 addition & 0 deletions macros/src/type/attr/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl_parse! {
"skip_deserializing" => out.skip = true,
"skip_serializing_if" => out.optional = attr.parse_string()? == *"Option::is_none",
"optional" => out.optional = attr.parse_bool().unwrap_or(true),
"default" => out.optional = attr.parse_bool().unwrap_or(true),
"flatten" => out.flatten = attr.parse_bool().unwrap_or(true)
}
}
Expand Down
29 changes: 3 additions & 26 deletions src/lang/ts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,25 +254,7 @@ fn object_datatype(
let mut unflattened_fields = fields
.iter()
.filter(|f| !f.flatten)
.map(|field| {
let ctx = ctx.with(PathItem::Field(field.key));
let field_name_safe = sanitise_key(field.key, false);
let field_ts_str = datatype_inner(ctx, &field.ty);

// https://github.com/oscartbeaumont/rspc/issues/100#issuecomment-1373092211
let (key, result) = match field.optional {
true => (
format!("{field_name_safe}?"),
match &field.ty {
DataType::Nullable(_) => field_ts_str,
_ => field_ts_str.map(|v| format!("{v} | null")),
},
),
false => (field_name_safe, field_ts_str),
};

result.map(|v| format!("{key}: {v}"))
})
.map(|f| object_field_to_ts(ctx.with(PathItem::Field(f.key)), f))
.collect::<Result<Vec<_>, _>>()?;

if let Some(tag) = tag {
Expand Down Expand Up @@ -384,14 +366,9 @@ impl LiteralType {
fn object_field_to_ts(ctx: ExportContext, field: &ObjectField) -> Result<String, TsExportError> {
let field_name_safe = sanitise_key(field.key, false);

// https://github.com/oscartbeaumont/rspc/issues/100#issuecomment-1373092211
let (key, ty) = match field.optional {
true => (
format!("{field_name_safe}?"),
match &field.ty {
DataType::Nullable(ty) => ty,
ty => ty,
},
),
true => (format!("{field_name_safe}?"), &field.ty),
false => (field_name_safe, &field.ty),
};

Expand Down
4 changes: 3 additions & 1 deletion tests/ts_rs/optional_field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ struct Optional {
b: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
c: Option<String>,
#[serde(default)]
d: bool,
}

#[test]
fn test() {
assert_ts!(
Optional,
"{ a: number | null; b?: number | null; c?: string | null }"
"{ a: number | null; b?: number | null; c?: string | null; d?: boolean }"
);
}

0 comments on commit 1e11212

Please sign in to comment.