StartRNR/cli/src/queries.rs
Kiana Sheibani badcec976a
Switch from surf to reqwest-blocking
Reqwest seems to be more popular, and a non-async API would simplify the
code without losing too much.
2023-09-02 01:36:28 -04:00

59 lines
1.6 KiB
Rust

use cynic::{GraphQlResponse, QueryBuilder};
use serde::{Deserialize, Serialize};
pub mod search_games;
pub use search_games::*;
pub mod tournament_sets;
pub use tournament_sets::*;
use schema::schema;
// Types
// HACK: Unfortunately, start.gg seems to use integers for its ID type, whereas
// cynic always assumes that IDs are strings. To get around that, we define a
// new scalar type that serializes to u64.
#[derive(cynic::Scalar, Debug, Copy, Clone)]
pub struct ID(pub u64);
// Wrapper types to differentiate between different types of IDs
#[derive(Debug, Copy, Clone)]
pub struct VideogameId(pub u64);
#[derive(Debug, Copy, Clone)]
pub struct EntrantId(pub u64);
#[derive(cynic::Scalar, Debug, Clone)]
pub struct Timestamp(pub u64);
// Query machinery
pub trait QueryUnwrap<Vars>: 'static + QueryBuilder<Vars> {
type VarsUnwrapped;
type Unwrapped;
fn wrap_vars(vars: Self::VarsUnwrapped) -> Vars;
fn unwrap_response(response: GraphQlResponse<Self>) -> Option<Self::Unwrapped>;
}
// Generic function for running start.gg queries
pub fn run_query<Builder, Vars>(
vars: Builder::VarsUnwrapped,
auth: &str,
) -> Option<Builder::Unwrapped>
where
Builder: QueryUnwrap<Vars>,
Vars: Serialize,
for<'de> Builder: Deserialize<'de>,
{
use cynic::http::ReqwestBlockingExt;
let query = Builder::build(Builder::wrap_vars(vars));
let response = reqwest::blocking::Client::new()
.post("https://api.start.gg/gql/alpha")
.header("Authorization", String::from("Bearer ") + auth)
.run_graphql(query);
Builder::unwrap_response(response.unwrap())
}