From e3161f2e8561089d6db72f2a36011c7a5b54f320 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Mon, 20 Aug 2018 15:23:35 +0200 Subject: Use builder pattern to construct items. --- src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/zotapi.rs | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7520475..4852a94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,6 +47,44 @@ impl From for Error { } } +pub struct ItemBuilder<'a> { + client : &'a Client, + body: &'a str, +} + +impl<'a> ItemBuilder<'a> { + fn new(client: &'a Client) -> ItemBuilder<'a> { + ItemBuilder { + client: client, + body: "", + } + } + pub fn body(&mut self, text: &'a str) -> &mut ItemBuilder<'a> { + self.body = text; + self + } + + 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) + } + } +} + pub struct Client { inner: reqwest::Client, base_url: String, @@ -63,6 +101,10 @@ impl Client { self.fetch_stream(ZOTAPI_NETWORK_STREAM_PATH) } + pub fn item(&self) -> ItemBuilder { + ItemBuilder::new(self) + } + pub fn create_item(&self, body: &str) -> Result { let url = self.url(ZOTAPI_ITEM_UPDATE_PATH); let mut res = self.inner.post(&url) diff --git a/tests/zotapi.rs b/tests/zotapi.rs index f8991f7..0437313 100644 --- a/tests/zotapi.rs +++ b/tests/zotapi.rs @@ -75,7 +75,7 @@ fn create_new_post() { .create(); let z = zotapi::client(&format!("http://{}", mockito::SERVER_ADDRESS), "testuser", "test1234"); - let res = z.create_item("This is a test"); + let _res = z.item().body("This is a test").create(); m.assert(); } -- cgit v1.2.3