From 0ad87fec2d09cfc65bc3674732d501e683e7ce63 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Mon, 20 Aug 2018 16:03:24 +0200 Subject: Refactoring: Make Client::post_data helper. This means we don't need to access internal data members of the Client in builder structs an the like. --- Cargo.toml | 1 + src/lib.rs | 42 +++++++++++++++++++++++++----------------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 455b826..ec8f852 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ authors = ["haraldei"] [dependencies] reqwest = "0.8" +serde = "1.0" [dev-dependencies] dotenv = "0.13" diff --git a/src/lib.rs b/src/lib.rs index 57724ad..0ebc364 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,12 +15,14 @@ // along with this program. If not, see . extern crate reqwest; +extern crate serde; use reqwest::{ header::{Accept, ContentType, qitem}, mime, StatusCode, }; +use serde::Serialize; use std::io::Read; const ZOTAPI_CHANNEL_STREAM_PATH : &str = "/api/z/1.0/channel/stream"; @@ -65,23 +67,7 @@ impl<'a> ItemBuilder<'a> { } pub fn create(&self) -> Result { - let url = self.client.url(ZOTAPI_ITEM_UPDATE_PATH); - let mut res = self.client.inner.post(&url) - .header(Accept(vec![qitem(mime::APPLICATION_JSON)])) - .header(ContentType::form_url_encoded()) - .basic_auth(self.client.user.clone(), Some(self.client.pw.clone())) - .form(&[("body", self.body)]) - .send()?; - - match res.status() { - StatusCode::Unauthorized => Err(Error::Unauthorized), - StatusCode::Ok => { - let mut body = String::new(); - res.read_to_string(&mut body)?; - Ok(body) - }, - _ => Err(Error::Unknown) - } + self.client.post_data(ZOTAPI_ITEM_UPDATE_PATH, &[("body", self.body)]) } } @@ -126,6 +112,28 @@ impl Client { _ => Err(Error::Unknown) } } + + fn post_data(&self, path: &str, data: &T) -> Result + where T: Serialize, + { + let url = self.url(path); + let mut res = self.inner.post(&url) + .header(Accept(vec![qitem(mime::APPLICATION_JSON)])) + .header(ContentType::form_url_encoded()) + .basic_auth(self.user.clone(), Some(self.pw.clone())) + .form(&data) + .send()?; + + match res.status() { + StatusCode::Unauthorized => Err(Error::Unauthorized), + StatusCode::Ok => { + let mut body = String::new(); + res.read_to_string(&mut body)?; + Ok(body) + }, + _ => Err(Error::Unknown) + } + } } pub fn client(url: &str, user: &str, pw: &str) -> Client -- cgit v1.2.3