StartRNR/cli/src/queries.rs

46 lines
1.3 KiB
Rust
Raw Normal View History

use std::fmt::{Display, Formatter};
use cynic::{GraphQlResponse, QueryBuilder};
use serde::{Deserialize, Serialize};
2023-08-26 23:48:13 -04:00
2023-08-27 03:02:18 -04:00
pub mod search_games;
2023-08-27 03:11:23 -04:00
use schema::schema;
// 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);
impl Display for ID {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
<u64 as Display>::fmt(&self.0, f)
}
}
2023-08-27 03:52:38 -04:00
pub trait QueryUnwrap<Vars>: QueryBuilder<Vars> {
type Unwrapped;
2023-08-27 03:52:38 -04:00
fn unwrap_response(response: GraphQlResponse<Self>) -> Option<Self::Unwrapped>;
}
2023-08-27 03:52:38 -04:00
// Generic function for running start.gg queries
pub async fn run_query<Builder: 'static, Vars>(vars: Vars, auth: &str) -> Option<Builder::Unwrapped>
where
Builder: QueryUnwrap<Vars>,
Vars: Serialize,
for<'de> Builder: Deserialize<'de>,
2023-08-27 03:52:38 -04:00
{
use cynic::http::SurfExt;
let query = Builder::build(vars);
let response = surf::post("https://api.start.gg/gql/alpha")
.header("Authorization", String::from("Bearer ") + auth)
.run_graphql(query)
.await;
<Builder as QueryUnwrap<Vars>>::unwrap_response(response.unwrap())
2023-08-27 03:52:38 -04:00
}