diff options
author | Harald Eilertsen <haraldei@anduin.net> | 2018-08-19 20:29:14 +0200 |
---|---|---|
committer | Harald Eilertsen <haraldei@anduin.net> | 2018-08-19 20:29:14 +0200 |
commit | 7e1ee802f03208c2a50ba73b7b9f8b841bddb54a (patch) | |
tree | 9790db1fd2da825be00d1348b9770d61ba8fc787 | |
parent | 225478bb8c19705ab865f209fe692eb426ea1e51 (diff) | |
download | rust-zotapi-7e1ee802f03208c2a50ba73b7b9f8b841bddb54a.tar.gz rust-zotapi-7e1ee802f03208c2a50ba73b7b9f8b841bddb54a.tar.bz2 rust-zotapi-7e1ee802f03208c2a50ba73b7b9f8b841bddb54a.zip |
First attempt at creating posts.
-rw-r--r-- | src/lib.rs | 23 | ||||
-rw-r--r-- | tests/zotapi.rs | 16 |
2 files changed, 38 insertions, 1 deletions
@@ -17,7 +17,7 @@ extern crate reqwest; use reqwest::{ - header::{Accept, qitem}, + header::{Accept, ContentType, qitem}, mime, StatusCode, }; @@ -25,6 +25,7 @@ use std::io::Read; const ZOTAPI_CHANNEL_STREAM_PATH : &str = "/api/z/1.0/channel/stream"; const ZOTAPI_NETWORK_STREAM_PATH : &str = "/api/z/1.0/network/stream"; +const ZOTAPI_ITEM_UPDATE_PATH : &str = "/api/z/1.0/item/update"; #[derive(Debug)] pub enum Error { @@ -62,6 +63,26 @@ impl Client { self.fetch_stream(ZOTAPI_NETWORK_STREAM_PATH) } + pub fn create_item(&self, body: &str) -> Result<String, Error> { + let url = self.url(ZOTAPI_ITEM_UPDATE_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(&[("body", 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) + } + } + fn url(&self, path: &str) -> String { self.base_url.clone() + path } diff --git a/tests/zotapi.rs b/tests/zotapi.rs index 90f5298..f8991f7 100644 --- a/tests/zotapi.rs +++ b/tests/zotapi.rs @@ -63,3 +63,19 @@ fn return_error_if_invalid_auth_provided() { assert!(data.is_err()); assert_eq!(format!("{:?}", data), "Err(Unauthorized)"); } + +#[test] +fn create_new_post() { + let m = mock("POST", "/api/z/1.0/item/update") + .match_header("Authorization", Matcher::Regex(r"Basic \w+".into())) + .match_body("body=This+is+a+test") + .with_status(200) + .with_header("content-type", "application/json") + .with_body("{}") + .create(); + + let z = zotapi::client(&format!("http://{}", mockito::SERVER_ADDRESS), "testuser", "test1234"); + let res = z.create_item("This is a test"); + + m.assert(); +} |