Skip to content

Commit

Permalink
Take body only required when extract data (#471)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn authored Oct 30, 2023
1 parent 6a58880 commit 8d72671
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
13 changes: 13 additions & 0 deletions crates/core/src/extract/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,14 @@ impl Metadata {
self.rename_all = rename_all.into();
self
}

/// Check is this type has body required.
pub(crate) fn has_body_required(&self) -> bool {
if self.default_sources.iter().any(|s| s.from == SourceFrom::Body) {
return true;
}
self.fields.iter().any(|f| f.has_body_required())
}
}

/// Information about struct field.
Expand Down Expand Up @@ -249,6 +257,11 @@ impl Field {
self.rename = Some(rename);
self
}

/// Check is this field has body required.
pub(crate) fn has_body_required(&self) -> bool {
self.sources.iter().any(|s| s.from == SourceFrom::Body)
}
}

/// Request source for extract data.
Expand Down
33 changes: 25 additions & 8 deletions crates/core/src/serde/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,21 @@ where
T: Deserialize<'de>,
{
// Ensure body is parsed correctly.
req.form_data().await.ok();
req.payload().await.ok();
if let Some(ctype) = req.content_type() {
match ctype.subtype() {
mime::WWW_FORM_URLENCODED | mime::FORM_DATA => {
if metadata.has_body_required() {
req.form_data().await.ok();
}
}
mime::JSON => {
if metadata.has_body_required() {
req.payload().await.ok();
}
}
_ => {}
}
}
Ok(T::deserialize(RequestDeserializer::new(req, metadata)?)?)
}

Expand Down Expand Up @@ -58,14 +71,18 @@ impl<'de> RequestDeserializer<'de> {
if let Some(ctype) = request.content_type() {
match ctype.subtype() {
mime::WWW_FORM_URLENCODED | mime::FORM_DATA => {
payload = request.form_data.get().map(Payload::FormData);
if metadata.has_body_required() {
payload = request.form_data.get().map(Payload::FormData);
}
}
mime::JSON => {
if let Some(data) = request.payload.get() {
payload = match serde_json::from_slice::<HashMap<&str, &RawValue>>(data) {
Ok(map) => Some(Payload::JsonMap(map)),
Err(_) => Some(Payload::JsonStr(std::str::from_utf8(data)?)),
};
if metadata.has_body_required() {
if let Some(data) = request.payload.get() {
payload = match serde_json::from_slice::<HashMap<&str, &RawValue>>(data) {
Ok(map) => Some(Payload::JsonMap(map)),
Err(_) => Some(Payload::JsonStr(std::str::from_utf8(data)?)),
};
}
}
}
_ => {}
Expand Down

0 comments on commit 8d72671

Please sign in to comment.