use super::http::get_request;
use super::API_URL;
use crate::error::NeocitiesErr;
use serde_derive::Deserialize;
use serde_derive::Serialize;
pub struct NcKey {}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiKeyResponse {
pub result: String,
#[serde(rename = "api_key")]
pub api_key: String,
}
impl NcKey {
fn prepare_url(user: String, password: String) -> String {
return format!("https://{}:{}@{}key", user, password, API_URL);
}
fn to_api_key_response(value: serde_json::Value) -> Result<ApiKeyResponse, NeocitiesErr> {
match serde_json::from_value(value) {
Ok(res) => Ok(res),
Err(e) => return Err(NeocitiesErr::SerdeDeserializationError(e)),
}
}
pub fn fetch(user: String, pass: String) -> Result<ApiKeyResponse, NeocitiesErr> {
let url = NcKey::prepare_url(user, pass);
let res = get_request(url, None)?;
let akr = NcKey::to_api_key_response(res)?;
Ok(akr)
}
}
#[cfg(test)]
mod tests {
use super::NcKey;
#[test]
fn key_url() {
let url = NcKey::prepare_url("foo".to_string(), "bar".to_string());
assert_eq!(url, "https://foo:bar@neocities.org/api/key");
}
#[test]
fn value_to_api_key_response() {
let str = r#"
{
"result": "Success",
"api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}"#;
let v: serde_json::Value = serde_json::from_str(str).unwrap();
let akr = NcKey::to_api_key_response(v).unwrap();
assert_eq!(akr.result, "Success");
assert_eq!(akr.api_key, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
}