From 9806d9e094271f76c99589d252a57117d35ae7e5 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Mon, 29 Jul 2019 11:02:32 +0200 Subject: Abstract away type of stored data in an Item. Currently this seems rather pointless, but will make more sense when we need to store arrays in the Item data set. --- src/client.rs | 3 ++- src/item.rs | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/client.rs b/src/client.rs index e1561bf..95643a1 100644 --- a/src/client.rs +++ b/src/client.rs @@ -128,7 +128,8 @@ impl Client { handle_result(res) } - pub fn post_multipart(&self, path: &str, data: &BTreeMap<&str, &str>, files: &Vec<&str>) -> Result + pub fn post_multipart(&self, path: &str, data: &BTreeMap<&str, T>, files: &Vec<&str>) -> Result + where T: ToString, { let url = dbg!(self.url(path, &())); let mut form = reqwest::multipart::Form::new(); diff --git a/src/item.rs b/src/item.rs index 510918f..09ec4c0 100644 --- a/src/item.rs +++ b/src/item.rs @@ -18,8 +18,41 @@ use crate::{ client::{self, Client}, error::Error, }; +use serde::{Serialize, Serializer}; use std::collections::BTreeMap; + +/// Data type for values that an Item can hold. +pub enum ItemData<'a> { + /// A single value, either textual or numeric. + Value(&'a str), +} + +impl<'a> From<&'a str> for ItemData<'a> { + fn from(orig: &'a str) -> ItemData<'a> { + ItemData::Value(orig) + } +} + +impl<'a> Serialize for ItemData<'a> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer + { + match &self { + ItemData::Value(s) => s.serialize(serializer), + } + } +} + +impl<'a> ToString for ItemData<'a> { + fn to_string(&self) -> String { + match &self { + ItemData::Value(s) => s.to_string(), + } + } +} + /// A structure to help you create an item in a declarative way. /// /// Typical usage: @@ -35,7 +68,7 @@ use std::collections::BTreeMap; /// ``` pub struct ItemBuilder<'a> { client : &'a Client, - data : BTreeMap<&'a str, &'a str>, + data : BTreeMap<&'a str, ItemData<'a>>, files: Vec<&'a str>, } @@ -50,13 +83,13 @@ impl<'a> ItemBuilder<'a> { /// Add a title to the post pub fn title(&mut self, text: &'a str) -> &mut ItemBuilder<'a> { - self.data.insert("title", text); + self.data.insert("title", ItemData::Value(text)); self } /// Add the body of the post pub fn body(&mut self, text: &'a str) -> &mut ItemBuilder<'a> { - self.data.insert("body", text); + self.data.insert("body", ItemData::Value(text)); self } -- cgit v1.2.3