chore(backend): cleaner code

Signed-off-by: Lucien Cartier-Tilet <lucien@phundrak.com>
This commit is contained in:
Lucien Cartier-Tilet 2023-03-15 16:35:34 +01:00
parent a1f29c71f6
commit 3448672fec
Signed by: phundrak
GPG Key ID: BD7789E705CB8DCA

View File

@ -1,43 +1,14 @@
use actix_web::{error, get, web, Responder, Result}; use actix_web::{error, get, web, Responder, Result};
use data::Data;
use derive_more::{Display, Error}; use derive_more::{Display, Error};
use dotenvy::dotenv; use dotenvy::dotenv;
use gql_client::Client; use gql_client::{Client, GraphQLError};
use std::collections::HashMap; use std::collections::HashMap;
mod data; mod data;
#[derive(Debug, Display, Error)] macro_rules! GITHUB_GRAPHQL_QUERY {
#[display(fmt = "my error: {}", name)] () => {
struct MyError {
name: String,
}
struct AppState {
github_token: String,
}
impl Default for AppState {
fn default() -> Self {
Self {
github_token: github_token(),
}
}
}
impl error::ResponseError for MyError {}
fn github_token() -> String {
std::env::var("GH_TOKEN")
.expect("Environment variable GH_TOKEN **MUST** be set!")
}
#[get("/phundrak-com/{user}")]
async fn user_info_github(
user: web::Path<String>,
state: web::Data<AppState>,
) -> Result<impl Responder> {
let gh_token = &state.github_token;
let body = format!(
r#"query {{ r#"query {{
user(login: "{}") {{ user(login: "{}") {{
newest: repositories(first: 10, orderBy: {{field: UPDATED_AT, direction: DESC}}) {{ newest: repositories(first: 10, orderBy: {{field: UPDATED_AT, direction: DESC}}) {{
@ -64,24 +35,78 @@ async fn user_info_github(
}} }}
}} }}
}} }}
}}"#, }}"#
user };
); }
#[derive(Debug, Display, Error)]
#[display(fmt = "my error: {}", name)]
struct MyError {
name: String,
}
struct AppState {
github_token: String,
}
impl Default for AppState {
fn default() -> Self {
Self {
github_token: github_token(),
}
}
}
impl error::ResponseError for MyError {}
fn github_token() -> String {
std::env::var("GH_TOKEN")
.expect("Environment variable GH_TOKEN **MUST** be set!")
}
fn prepare_github_query_headers(gh_token: &String) -> HashMap<String, String> {
let mut headers: HashMap<String, String> = HashMap::new(); let mut headers: HashMap<String, String> = HashMap::new();
headers.insert("Authorization".to_string(), format!("Bearer {}", gh_token)); headers.insert("Authorization".to_string(), format!("Bearer {}", gh_token));
headers.insert("User-Agent".to_string(), "PhunCache-App".to_string()); headers.insert("User-Agent".to_string(), "PhunCache-App".to_string());
let client = headers
Client::new_with_headers("https://api.github.com/graphql", headers); }
client
.query::<data::Data>(&body) fn make_gh_graphql_client(gh_token: &String) -> Client {
.await let headers = prepare_github_query_headers(gh_token);
.map(web::Json) Client::new_with_headers("https://api.github.com/graphql", headers)
.map_err(|e| { }
MyError {
async fn make_gh_graphql_call(
user: String,
gh_token: &String,
) -> Result<Option<Data>, GraphQLError> {
let body = format!(GITHUB_GRAPHQL_QUERY!(), user);
let client = make_gh_graphql_client(gh_token);
let data = client.query::<Data>(&body).await;
println!("{:?}", data);
data
}
#[get("/phundrak-com/{user}")]
async fn user_info_github(
user: web::Path<String>,
state: web::Data<AppState>,
) -> Result<impl Responder> {
let gh_token = &state.github_token;
match make_gh_graphql_call(user.to_string(), gh_token).await {
Ok(val) => Ok(web::Json(val)),
Err(e) => Err(MyError {
name: format!("Failed to retrieve data from GitHub: {e:?}"), name: format!("Failed to retrieve data from GitHub: {e:?}"),
} }
.into() .into()),
}) }
}
fn setup_application() {
std::env::set_var("RUST_LOG", "debug");
env_logger::init();
dotenv().ok();
human_panic::setup_panic!();
} }
#[actix_web::main] #[actix_web::main]
@ -89,10 +114,7 @@ async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
use std::env::var; use std::env::var;
std::env::set_var("RUST_LOG", "debug"); setup_application();
env_logger::init();
dotenv().ok();
human_panic::setup_panic!();
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()