Skip to main content

bast3st_eval/spec/runtime/
network.rs

1use std::{collections::BTreeMap, sync::Arc};
2
3use derive_getters::Getters;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    catchable::cerr,
8    spec::{MapKey, RealMapping, Text, runtime::RuntimeValue},
9};
10
11#[derive(Debug, PartialEq, PartialOrd, Clone, Getters)]
12pub struct NetworkRequest {
13    server: Text,
14    route: Text,
15    specific: InnerNetworkRequest,
16}
17impl NetworkRequest {
18    pub fn new_get(server: Text, route: Text) -> Self {
19        Self {
20            server,
21            route,
22            specific: InnerNetworkRequest::Get,
23        }
24    }
25    pub fn new_post(server: Text, route: Text, json: Option<Vec<(Text, RuntimeValue)>>) -> Self {
26        Self {
27            server,
28            route,
29            specific: InnerNetworkRequest::Post {
30                json: json.map(|x| x.into()),
31            },
32        }
33    }
34    pub fn into_specific(self) -> InnerNetworkRequest {
35        self.specific
36    }
37}
38
39#[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum InnerNetworkRequest {
42    Get,
43    #[serde(rename_all = "kebab-case")]
44    Post {
45        json: Option<Arc<[(Text, RuntimeValue)]>>,
46    },
47}
48
49#[derive(Debug, PartialEq, PartialOrd, Clone, Serialize, Deserialize)]
50pub struct NetworkResponse {
51    status: u16,
52    url: Text,
53    text: Text,
54    json: Result<RuntimeValue, cerr>,
55}
56impl NetworkResponse {
57    pub fn status(&self) -> u16 {
58        self.status
59    }
60    pub async fn new(value: reqwest::Response) -> Result<Self, cerr> {
61        let status = value.status().as_u16();
62        let url = value.url().to_string().into();
63        let text = value.text().await.map_err(|_| cerr::network_external)?;
64        let json: Result<RuntimeValue, cerr> =
65            serde_json::from_str::<serde_json::Value>(text.as_str())
66                .map_err(|_| cerr::network_respInvalid_notJson)
67                .map(RuntimeValue::from);
68        Ok(NetworkResponse {
69            status,
70            url,
71            json,
72            text: text.into(),
73        })
74    }
75}
76
77impl From<NetworkResponse> for RealMapping {
78    fn from(value: NetworkResponse) -> Self {
79        let mut mapping: BTreeMap<MapKey, Result<RuntimeValue, cerr>> = BTreeMap::new();
80        mapping.insert("status".into(), Ok(value.status.into()));
81        mapping.insert("url".into(), Ok(value.url.into()));
82        mapping.insert("text".into(), Ok(value.text.into()));
83        mapping.insert("json".into(), value.json);
84        mapping.into()
85    }
86}