Serialize an empty JSON object as body for responses without body fields

This commit is contained in:
Jonas Platte 2020-04-15 22:04:27 +02:00
parent 2bbcfda3fd
commit 0238a72b59
No known key found for this signature in database
GPG Key ID: CC154DE0E30B7C67
2 changed files with 49 additions and 21 deletions

View File

@ -100,10 +100,6 @@ impl Response {
return quote_spanned!(span=> response.#field_name);
}
if !self.has_body_fields() && self.newtype_body_field().is_none() {
return quote!(Vec::new());
}
let body = if let Some(field) = self.newtype_body_field() {
let field_name = field.ident.as_ref().expect("expected field to have an identifier");
let span = field.span();
@ -248,7 +244,7 @@ impl ToTokens for Response {
quote! { { #(#fields),* } }
};
let response_body_struct =
let (derive_deserialize, def) =
if let Some(body_field) = self.fields.iter().find(|f| f.is_newtype_body()) {
let field = Field { ident: None, colon_token: None, ..body_field.field().clone() };
let derive_deserialize = if body_field.has_wrap_incoming_attr() {
@ -257,7 +253,7 @@ impl ToTokens for Response {
quote!(ruma_api::exports::serde::Deserialize)
};
Some((derive_deserialize, quote! { (#field); }))
(derive_deserialize, quote! { (#field); })
} else if self.has_body_fields() {
let fields = self.fields.iter().filter(|f| f.is_body());
let derive_deserialize = if fields.clone().any(|f| f.has_wrap_incoming_attr()) {
@ -267,22 +263,21 @@ impl ToTokens for Response {
};
let fields = fields.map(ResponseField::field);
Some((derive_deserialize, quote!({ #(#fields),* })))
(derive_deserialize, quote!({ #(#fields),* }))
} else {
None
}
.map(|(derive_deserialize, def)| {
quote! {
/// Data in the response body.
#[derive(
Debug,
ruma_api::Outgoing,
ruma_api::exports::serde::Serialize,
#derive_deserialize
)]
struct ResponseBody #def
}
});
(TokenStream::new(), quote!({}))
};
let response_body_struct = quote! {
/// Data in the response body.
#[derive(
Debug,
ruma_api::Outgoing,
ruma_api::exports::serde::Serialize,
#derive_deserialize
)]
struct ResponseBody #def
};
let response = quote! {
#[derive(Debug, Clone, ruma_api::Outgoing)]

33
tests/no_fields.rs Normal file
View File

@ -0,0 +1,33 @@
use std::convert::TryFrom;
use ruma_api_macros::ruma_api;
ruma_api! {
metadata {
description: "Does something.",
method: GET,
name: "no_fields",
path: "/_matrix/my/endpoint",
rate_limited: false,
requires_authentication: false,
}
request {}
response {}
}
#[test]
fn empty_request_http_repr() {
let req = Request {};
let http_req = http::Request::<Vec<u8>>::try_from(req).unwrap();
assert!(http_req.body().is_empty());
}
#[test]
fn empty_response_http_repr() {
let res = Response {};
let http_res = http::Response::<Vec<u8>>::try_from(res).unwrap();
assert_eq!(http_res.body(), b"{}");
}