1use anyhow::Result;
2use serde_json::{json, Value};
3
4pub struct Api {
5 pub token: String,
6}
7
8impl Api {
9 pub fn client(&self) -> reqwest::RequestBuilder {
10 let client = reqwest::Client::new();
11 client
12 .post(format!("https://gw.twetch.app"))
13 .header("Authorization", format!("Bearer {}", self.token))
14 }
15
16 pub async fn graphql(&self, query: String, variables: Option<Value>) -> Result<Value> {
17 let payload = json!({
18 "operationName": null,
19 "variables": variables,
20 "query": query
21 });
22
23 println!("api payload {:?}", payload);
24
25 let res = self
26 .client()
27 .json(&payload)
28 .send()
29 .await?
30 .json::<Value>()
31 .await?;
32
33 println!("res {:?}", res);
34
35 let data = res.get("data").unwrap().clone();
36
37 println!("data {:?}", data);
38
39 Ok(data)
40 }
41
42 pub async fn create_message(&self, payload: Value) -> Result<Value> {
43 let query = format!(
44 "mutation createMessage($payload: MessageInput!) {{ createMessage(input: {{ message: $payload }}) {{ messageEdge {{ node {{ id }} }} }} }}",
45 );
46
47 let res = self
48 .graphql(query, Some(payload))
49 .await?
50 .get("createMessage")
51 .unwrap()
52 .clone();
53 Ok(res)
54 }
55
56 pub async fn create_conversation(&self, payload: String) -> Result<Value> {
57 let query = format!(
58 "mutation createConversation($payload: String!) {{ createConversation(input: {{ payload: $payload }}) {{ id }} }}",
59 );
60
61 let res = self
62 .graphql(
63 query,
64 Some(json!({ "payload": serde_json::to_value(payload).unwrap() })),
65 )
66 .await?
67 .get("createConversation")
68 .unwrap()
69 .clone();
70 Ok(res)
71 }
72
73 pub async fn list_pubkeys(&self, user_ids: Vec<String>) -> Result<Value> {
74 let user_ids_string = serde_json::to_value(user_ids).unwrap().to_string();
75 let query = format!(
76 "query ListPubkeys {{ allUsers(filter: {{ id: {{ in: {} }} }}) {{ nodes {{ publicKey }} }} }} ",
77 user_ids_string
78 );
79 let res = self
80 .graphql(query, None)
81 .await?
82 .get("allUsers")
83 .unwrap()
84 .get("nodes")
85 .unwrap()
86 .clone();
87 Ok(res)
88 }
89}