fix-graphql-interface

This commit is contained in:
Untone 2023-10-13 00:46:55 +03:00
parent a31d667675
commit f369d3104e

View File

@ -1,61 +1,88 @@
use reqwest::Client as HTTPClient; 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::collections::HashMap;
use std::error::Error; use std::error::Error;
use std::env; use std::env;
pub async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> { pub async fn get_auth_id(token: &str) -> Result<i32, Box<dyn Error>> {
let auth_api_base = env::var("AUTH_URL")?; let auth_api_base = env::var("AUTH_URL")?;
let (query_name, query_type) = match auth_api_base.contains("discours.io") { let (query_name, query_type) = match auth_api_base.contains("auth.discours.io") {
true => ("getSession", "mutation"), // v2 _ => ("getSession", "mutation"), // v2
_ => ("session", "query") // authorizer 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#"{{ let gql = json!({
"query": "{} GetSession {{ {} {{ user {{ id }} }} }}", "query": format!("{} {} {{ {} {{ user {{ id }} }} }}", query_type, operation, query_name),
"operationName": "GetSession", "operationName": operation,
"variables": {{}} "variables": HashMap::<String, String>::new()
}}"#, query_type, query_name); });
let client = HTTPClient::new(); let client = reqwest::Client::new();
let response = client let response = client.post(&auth_api_base)
.post(auth_api_base) .headers(headers)
.bearer_auth(token) // NOTE: auth token is here .json(&gql)
.body(body)
.send() .send()
.await?; .await?;
let response_body: Value = response.json().await?;
let id = response_body["data"][query_name]["user"]["id"] if response.status().is_success() {
.as_i64() let r: HashMap<String, serde_json::Value> = response.json().await?;
.ok_or("Failed to get user id by token")? as i32; let user_id = r.get("data")
Ok(id) .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<Vec<i32>, Box<dyn Error>> { async fn get_shout_followers(shout_id: &str) -> Result<Vec<i32>, Box<dyn Error>> {
let api_base = env::var("API_BASE")?; let api_base = env::var("API_BASE")?;
let gql = format!(r#"query ShoutFollowers {{ let query = r#"query ShoutFollowers($shout: Int!) {
shoutFollowers(shout: {}) {{ shoutFollowers(shout: $shout) {
follower {{ follower {
id id
}} }
}} }
}} }
"#, shout_id); "#;
let body = format!(r#"{{ let shout_id = shout_id.parse::<i32>()?;
"query": "{}", let variables = json!({
"shout": shout_id
});
let body = json!({
"query": query,
"operationName": "ShoutFollowers", "operationName": "ShoutFollowers",
"variables": {{}} "variables": variables
}}"#, gql); });
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let response = client let response = client
.post(&api_base) .post(&api_base)
.body(body) .json(&body)
.send() .send()
.await?; .await?;
if response.status().is_success() {
let response_body: serde_json::Value = response.json().await?; let response_body: serde_json::Value = response.json().await?;
let ids: Vec<i32> = response_body["data"]["shoutFollowers"] let ids: Vec<i32> = response_body["data"]["shoutFollowers"]
.as_array() .as_array()
.ok_or("Failed to parse follower array")? .ok_or("Failed to parse follower array")?
@ -64,6 +91,10 @@ async fn get_shout_followers(shout_id: &str) -> Result<Vec<i32>, Box<dyn Error>>
.collect(); .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()))))
}
} }