1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use percent_encoding::{percent_encode, AsciiSet, NON_ALPHANUMERIC};
use serde_json::{Map, Value};
use url::Url;

use crate::endpoints::URL_BASE;

pub const GRAPHQL_QUERY_URL_PERCENT_ENCODE_ASCII_SET: &AsciiSet =
    &NON_ALPHANUMERIC.remove(b'_').remove(b'-');

pub fn gen_a_url(mut url: Url) -> Url {
    url.query_pairs_mut().append_pair("__a", "1");
    url
}

pub fn gen_graphql_query_url(
    query_hash: impl AsRef<str>,
    variables: Map<String, Value>,
) -> Result<String, String> {
    let mut query_pairs = vec![("query_hash", query_hash.as_ref().to_owned())];

    let variables = serde_json::to_string(&Value::Object(variables))
        .map_err(|err| format!("to variables failed {}", err))?;
    query_pairs.push((
        "variables",
        percent_encode(
            variables.as_bytes(),
            GRAPHQL_QUERY_URL_PERCENT_ENCODE_ASCII_SET,
        )
        .to_string(),
    ));

    Ok(format!(
        "{}/graphql/query/?{}",
        URL_BASE,
        query_pairs
            .into_iter()
            .map(|x| format!("{}={}", x.0, x.1))
            .collect::<Vec<String>>()
            .join("&"),
    ))
}