get-author-connector

This commit is contained in:
Untone 2023-12-13 18:55:26 +03:00
parent 3958ae1062
commit 408957f4c8

View File

@ -7,6 +7,61 @@ use std::error::Error;
use crate::SSEMessageData;
async fn get_author_id(user: &str) -> Result<i32, Box<dyn Error>> {
let api_base = env::var("API_BASE")?;
let query_name = "get_author";
let operation = "GetAuthor";
let mut headers = HeaderMap::new();
// headers.insert(AUTHORIZATION, HeaderValue::from_str(token)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
let mut variables = HashMap::<String, String>::new();
variables.insert("user".to_string(), user.to_string());
let gql = json!({
"query": format!("query {} {{ {}(slug: String, user: String, author_id: Int){{ id }} }}", operation, query_name),
"operationName": operation,
"variables": variables
});
let client = HTTPClient::new();
let response = client
.post(&api_base)
.headers(headers)
.json(&gql)
.send()
.await?;
if response.status().is_success() {
let r: HashMap<String, serde_json::Value> = response.json().await?;
let author_id = r
.get("data")
.and_then(|data| data.get(query_name))
.and_then(|claims| claims.get("id"))
.and_then(|id| id.as_i64());
match author_id {
Some(id) => {
println!("Author ID retrieved: {}", id);
Ok(id as i32)
}
None => {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"No author ID found in the response",
)))
}
}
} else {
Err(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Request failed with status: {}", response.status()),
)))
}
}
pub async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> {
let auth_api_base = env::var("AUTH_URL")?;
let query_name = "validate_jwt_token";
@ -40,12 +95,15 @@ pub async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> {
.and_then(|data| data.get(query_name))
.and_then(|query| query.get("claims"))
.and_then(|claims| claims.get("sub"))
.and_then(|id| id.as_i64());
.and_then(|id| id.as_str());
// TODO: add get_author call to API_BASE to get author_id from user_id
match user_id {
Some(id) => {
println!("User ID retrieved: {}", id);
Ok(id as i32)
let author_id = get_author_id(id).await?;
Ok(author_id as i32)
}
None => {
println!("No user ID found in the response");