Skip to content

Instantly share code, notes, and snippets.

@miketwenty1
Created December 12, 2022 03:58
Show Gist options
  • Save miketwenty1/b4b39a6e09414eb25ab2a674c5b3bb28 to your computer and use it in GitHub Desktop.
Save miketwenty1/b4b39a6e09414eb25ab2a674c5b3bb28 to your computer and use it in GitHub Desktop.
Generics with builder example ideas for rust
use std::default;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FakeBodyStruct {
pub success: bool,
pub data: String,
}
#[derive(Debug, Default)]
pub enum MethodType {
#[default]
Get,
Post,
}
#[derive(Debug, Clone)]
pub struct Request<T> {
url: String,
method: Option<String>,
headers: Option<Vec<(String, String)>>,
body: Option<T>,
}
#[derive(Clone)]
pub struct RequestBuilder<T>
// where
// T: Serialize + DeserializeOwned,
{
url: Option<String>,
method: Option<String>,
headers: Option<Vec<(String, String)>>,
body: Option<T>,
}
impl<T: Clone + Serialize + DeserializeOwned> Default for RequestBuilder<T> {
fn default() -> Self {
RequestBuilder {
url: Default::default(),
method: Default::default(),
headers: Default::default(),
body: Default::default(),
}
}
}
// impl<T: Serialize + DeserializeOwned> Clone for RequestBuilder<T> {
// fn clone(&self) -> Self {
// RequestBuilder {
// url: self.url.clone(),
// method: self.method.clone(),
// headers: self.headers.clone(),
// body: self.body.clone(),
// }
// }
// }
impl<T: Clone + Serialize + DeserializeOwned> RequestBuilder<T> {
pub fn new() -> Self {
RequestBuilder::default()
}
pub fn url(&mut self, url: impl Into<String>) -> &mut Self {
self.url = Some(url.into());
self
}
pub fn method(&mut self, method: impl Into<String>) -> &mut Self {
self.method = Some(method.into());
self
}
pub fn header(&mut self, name: impl Into<String>, value: impl Into<String>) -> &mut Self {
if let Some(ref mut v) = self.headers {
v.push((name.into(), value.into()));
}
self
}
pub fn body(&mut self, body: T) -> &mut Self {
self.body = Some(body.into());
self
}
pub fn build(&self) -> Result<Request<T>, anyhow::Error> {
let Some(url) = self.url.as_ref() else {
return Err(anyhow::anyhow!("Error: missing url"));
};
let method = self
.method
.as_ref()
.cloned()
.unwrap_or_else(|| "GET".to_string());
Ok(Request {
url: "url".to_string(),
method: Some(method),
headers: self.headers.clone(),
body: self.body.clone(),
})
}
}
// fn hello() -> i32 {
// let f = FakeBodyStruct {
// success: true,
// data: "asdf".to_string(),
// };
// let r = RequestBuilder {
// url: "asdf".to_string(),
// method: Some(MethodType::Get),
// headers: 3,
// body: Some(f),
// };
// 3
// }
// pub fn url(&mut self, url: impl Into<String>) -> &mut RequestBuilder<T> {
// self.url = Some(url.into());
// self
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment