Use serde::Serialize instead of Display (helpers.rs)

This commit is contained in:
Temirkhan Myrzamadi 2019-09-03 13:01:36 +06:00
parent d3dc4e3f9a
commit 47d56c7ddd
3 changed files with 12 additions and 10 deletions

View file

@ -1,13 +1,14 @@
use reqwest::r#async::multipart::Form; use reqwest::r#async::multipart::Form;
use std::fmt::Display; use serde::Serialize;
/// Adds a key-value pair to the supplied form if `value` is some. Don't forget to implement `std::fmt::Display` for `T`! /// Adds a key-value pair to the supplied form if `value` is some. Don't forget
pub fn add_to_form_if_some<T>(form: Form, name: &str, value: Option<T>) -> Form /// to implement `serde::Serialize` for `T`!
pub fn add_to_form_if_some<T>(form: Form, name: &str, value: Option<&T>) -> Form
where where
T: Display, T: Serialize,
{ {
value.map_or_else( value.map_or_else(
|| form, || form,
|value| form.text(name.to_owned(), format!("{}", value)), |value| form.text(name.to_owned(), serde_json::to_string(value).expect("Failed to serialize a value to JSON")),
) )
} }

View file

@ -18,7 +18,8 @@ pub trait Request {
fn token(&self) -> &str; fn token(&self) -> &str;
} }
/// Unique identifier for the target chat or username of the target channel (in the format @channelusername) /// Unique identifier for the target chat or username of the target channel (in
/// the format @channelusername)
#[derive(Debug, Display, Serialize, From, PartialEq, Eq)] #[derive(Debug, Display, Serialize, From, PartialEq, Eq)]
pub enum ChatId { pub enum ChatId {
/// chat identifier /// chat identifier

View file

@ -34,16 +34,16 @@ impl Request for SendMessage {
let params = Form::new() let params = Form::new()
.text("chat_id", format!("{}", self.chat_id)) .text("chat_id", format!("{}", self.chat_id))
.text("text", self.text); .text("text", self.text);
let params = helpers::add_to_form_if_some(params, "parse_mode", self.parse_mode); let params = helpers::add_to_form_if_some(params, "parse_mode",self.parse_mode.as_ref());
let params = helpers::add_to_form_if_some( let params = helpers::add_to_form_if_some(
params, params,
"disable_web_page_preview", "disable_web_page_preview",
self.disable_web_page_preview, self.disable_web_page_preview.as_ref(),
); );
let params = let params =
helpers::add_to_form_if_some(params, "disable_notification", self.disable_notification); helpers::add_to_form_if_some(params, "disable_notification", self.disable_notification.as_ref());
let params = let params =
helpers::add_to_form_if_some(params, "reply_to_message_id", self.reply_to_message_id); helpers::add_to_form_if_some(params, "reply_to_message_id", self.reply_to_message_id.as_ref());
// TODO: // TODO:
// helpers::add_to_form_if_some( // helpers::add_to_form_if_some(