use crate::{Cache, PrintableGrid, State, TakoyakiError};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::Serialize;
use std::{collections::HashMap, str::FromStr};
pub struct Takoyaki;
pub struct Request<'a, T>
where
T: Serialize,
{
url: &'a str,
headers: HashMap<&'a str, &'a str>,
body: &'a T,
}
#[derive(Default, Clone, PartialEq, Debug, Eq)]
pub struct Pick<'a> {
pub array_root: &'a str,
pub weeks_root: &'a str,
pub color_key: &'a str,
pub contribution_count_key: &'a str,
}
pub fn convert_to_headermap(headers: HashMap<&str, &str>) -> HeaderMap {
let mut headermap = HeaderMap::new();
headers.iter().for_each(|(k, v)| {
headermap.insert(
HeaderName::from_str(k).unwrap(),
HeaderValue::from_str(v).unwrap(),
);
});
headermap
}
impl Takoyaki {
pub async fn run<T>(
mut request: Request<'_, T>,
pick: Pick<'_>,
) -> Result<(), TakoyakiError>
where
T: Serialize,
{
let client = reqwest::Client::new();
request.headers.insert("User-Agent", "takoyaki");
let builder = client
.post(request.url)
.headers(convert_to_headermap(request.headers))
.json(request.body);
let state = State::new(builder, Cache::new("github"));
let data = state.resolve::<serde_json::Value>().await?;
let mut printable = PrintableGrid::new(pick, data);
printable.pretty_print()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use serde::Serialize;
use crate::{Pick, Takoyaki};
#[tokio::test]
async fn it_works() {
let mut headers = HashMap::new();
#[derive(Serialize)]
pub struct Body {
query: String,
}
let body = Body {
query: String::from(
r#"
query {
user(login: "kyeboard") {
name
contributionsCollection {
contributionCalendar {
colors
totalContributions
weeks {
contributionDays {
color
contributionCount
date
weekday
}
firstDay
}
}
}
}
}
"#,
),
};
headers.insert("Authorization", "bearer ");
Takoyaki::run(
crate::Request {
url: "https://api.github.com/graphql",
headers,
body: &body,
},
Pick {
array_root: "data.user.contributionsCollection.contributionCalendar.weeks",
color_key: "color",
contribution_count_key: "contributionCount",
weeks_root: "contributionDays",
},
)
.await
.unwrap();
}
}