From 408957f4c82ad3303e1a296c4df06bcb113ec495 Mon Sep 17 00:00:00 2001 From: Untone Date: Wed, 13 Dec 2023 18:55:26 +0300 Subject: [PATCH] get-author-connector --- src/data.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/src/data.rs b/src/data.rs index 092d70d..62764fe 100644 --- a/src/data.rs +++ b/src/data.rs @@ -7,6 +7,61 @@ use std::error::Error; use crate::SSEMessageData; + +async fn get_author_id(user: &str) -> Result> { + 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::::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 = 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> { 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> { .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");