From f369d3104e5c96771bca31a4b31f7ecec98bbe2d Mon Sep 17 00:00:00 2001 From: Untone Date: Fri, 13 Oct 2023 00:46:55 +0300 Subject: [PATCH] fix-graphql-interface --- src/data.rs | 113 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 72 insertions(+), 41 deletions(-) diff --git a/src/data.rs b/src/data.rs index d11ca4f..fc28670 100644 --- a/src/data.rs +++ b/src/data.rs @@ -1,69 +1,100 @@ use reqwest::Client as HTTPClient; -use serde_json::Value; +use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE}; +use serde_json::{Value, json}; use std::collections::HashMap; use std::error::Error; use std::env; pub async fn get_auth_id(token: &str) -> Result> { let auth_api_base = env::var("AUTH_URL")?; - let (query_name, query_type) = match auth_api_base.contains("discours.io") { - true => ("getSession", "mutation"), // v2 - _ => ("session", "query") // authorizer + let (query_name, query_type) = match auth_api_base.contains("auth.discours.io") { + _ => ("getSession", "mutation"), // v2 + true => ("session", "query") // authorizer }; + let operation = "GetUserId"; + let mut headers = HeaderMap::new(); + headers.insert(AUTHORIZATION, HeaderValue::from_str(token)?); + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); - let body = format!(r#"{{ - "query": "{} GetSession {{ {} {{ user {{ id }} }} }}", - "operationName": "GetSession", - "variables": {{}} - }}"#, query_type, query_name); - - let client = HTTPClient::new(); - let response = client - .post(auth_api_base) - .bearer_auth(token) // NOTE: auth token is here - .body(body) + let gql = json!({ + "query": format!("{} {} {{ {} {{ user {{ id }} }} }}", query_type, operation, query_name), + "operationName": operation, + "variables": HashMap::::new() + }); + + let client = reqwest::Client::new(); + let response = client.post(&auth_api_base) + .headers(headers) + .json(&gql) .send() .await?; - let response_body: Value = response.json().await?; - let id = response_body["data"][query_name]["user"]["id"] - .as_i64() - .ok_or("Failed to get user id by token")? as i32; - Ok(id) + + if response.status().is_success() { + let r: HashMap = response.json().await?; + let user_id = r.get("data") + .and_then(|data| data.get(query_name)) + .and_then(|query| query.get("user")) + .and_then(|user| user.get("id")) + .and_then(|id| id.as_i64()); + + match user_id { + Some(id) => { + println!("User ID retrieved: {}", id); + Ok(id as i32) + }, + None => { + println!("No user ID found in the response"); + Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, "No user ID found in the response"))) + } + } + } else { + println!("Request failed with status: {}", response.status()); + Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, format!("Request failed with status: {}", response.status())))) + } } async fn get_shout_followers(shout_id: &str) -> Result, Box> { let api_base = env::var("API_BASE")?; - let gql = format!(r#"query ShoutFollowers {{ - shoutFollowers(shout: {}) {{ - follower {{ + let query = r#"query ShoutFollowers($shout: Int!) { + shoutFollowers(shout: $shout) { + follower { id - }} - }} - }} - "#, shout_id); - let body = format!(r#"{{ - "query": "{}", + } + } + } + "#; + let shout_id = shout_id.parse::()?; + let variables = json!({ + "shout": shout_id + }); + let body = json!({ + "query": query, "operationName": "ShoutFollowers", - "variables": {{}} - }}"#, gql); + "variables": variables + }); + let client = reqwest::Client::new(); let response = client .post(&api_base) - .body(body) + .json(&body) .send() .await?; - let response_body: serde_json::Value = response.json().await?; + if response.status().is_success() { + let response_body: serde_json::Value = response.json().await?; + let ids: Vec = response_body["data"]["shoutFollowers"] + .as_array() + .ok_or("Failed to parse follower array")? + .iter() + .filter_map(|f| f["follower"]["id"].as_i64().map(|id| id as i32)) + .collect(); - let ids: Vec = response_body["data"]["shoutFollowers"] - .as_array() - .ok_or("Failed to parse follower array")? - .iter() - .filter_map(|f| f["follower"]["id"].as_i64().map(|id| id as i32)) - .collect(); - - Ok(ids) + Ok(ids) + } else { + println!("Request failed with status: {}", response.status()); + Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, format!("Request failed with status: {}", response.status())))) + } }