mixin_sdk/
request.rs

1use crypto_hash::{hex_digest, Algorithm};
2use hyper::{Body, Client, Method, Request};
3use hyper_tls::HttpsConnector;
4use serde::{Deserialize, Serialize};
5use std::error::Error;
6
7#[derive(Serialize, Deserialize)]
8pub struct ErrorData {
9  pub error: ErrorInfo,
10}
11
12#[derive(Serialize, Deserialize)]
13pub struct ErrorInfo {
14  pub status: usize,
15  pub code: usize,
16  pub description: String,
17}
18
19#[derive(Serialize, Deserialize)]
20pub struct SuccessData<T> {
21  data: T,
22}
23
24#[derive(Serialize, Deserialize)]
25pub struct Version {
26  pub build: String,
27  pub developers: String,
28  pub timestamp: String,
29}
30
31const BASE_URL: &str = "https://api.mixin.one";
32pub async fn get<T>(token: String, url: &str) -> Result<T, Box<dyn Error>>
33where
34  T: serde::de::DeserializeOwned,
35{
36  let https = HttpsConnector::new();
37  let client = Client::builder().build::<_, Body>(https);
38  let res = client
39    .request(
40      Request::builder()
41        .method(Method::GET)
42        .header("Content-Type", "application/json")
43        .header("Authorization", format!("Bearer {}", token))
44        .uri(format!("{}{}", BASE_URL, url))
45        .body(Body::empty())
46        .unwrap(),
47    )
48    .await?;
49  let body = res.into_body();
50  let body = hyper::body::to_bytes(body).await?;
51  let body: SuccessData<T> = serde_json::from_slice(&body.slice(..)).unwrap();
52  Ok(body.data)
53}
54
55pub async fn post<T>(token: String, url: &str, body: Body) -> Result<T, Box<dyn Error>>
56where
57  T: serde::de::DeserializeOwned,
58{
59  let https = HttpsConnector::new();
60  let client = Client::builder().build::<_, Body>(https);
61  let res = client
62    .request(
63      Request::builder()
64        .method(Method::POST)
65        .header("Content-Type", "application/json")
66        .header("Authorization", format!("Bearer {}", token))
67        .uri(format!("{}{}", BASE_URL, url))
68        .body(body)
69        .unwrap(),
70    )
71    .await?;
72  let body = res.into_body();
73  let body = hyper::body::to_bytes(body).await?;
74  let body: SuccessData<T> = serde_json::from_slice(&body.slice(..)).unwrap();
75  Ok(body.data)
76}
77
78pub fn sign_request(method: &str, url: &str, body: &str) -> String {
79  let payload = format!("{}{}{}", method.to_uppercase(), url, body);
80  hex_digest(Algorithm::SHA256, payload.as_bytes())
81}