nullnet_libipinfo/api/
api_fields.rs

1use serde_json::Value;
2
3/// Struct to map the field names that can be extracted from the response of a given API provider.
4pub struct ApiFields {
5    pub country: Option<&'static str>,
6    pub asn: Option<&'static str>,
7    pub org: Option<&'static str>,
8    pub continent_code: Option<&'static str>,
9    pub city: Option<&'static str>,
10    pub region: Option<&'static str>,
11    pub postal: Option<&'static str>,
12    pub timezone: Option<&'static str>,
13}
14
15impl ApiFields {
16    pub(crate) fn extract_country(&self, json: &Value) -> Option<String> {
17        extract_json_field(json, self.country)
18    }
19
20    pub(crate) fn extract_asn(&self, json: &Value) -> Option<String> {
21        extract_json_field(json, self.asn)
22    }
23
24    pub(crate) fn extract_org(&self, json: &Value) -> Option<String> {
25        extract_json_field(json, self.org)
26    }
27
28    pub(crate) fn extract_continent_code(&self, json: &Value) -> Option<String> {
29        extract_json_field(json, self.continent_code)
30    }
31
32    pub(crate) fn extract_city(&self, json: &Value) -> Option<String> {
33        extract_json_field(json, self.city)
34    }
35
36    pub(crate) fn extract_region(&self, json: &Value) -> Option<String> {
37        extract_json_field(json, self.region)
38    }
39
40    pub(crate) fn extract_postal(&self, json: &Value) -> Option<String> {
41        extract_json_field(json, self.postal)
42    }
43
44    pub(crate) fn extract_timezone(&self, json: &Value) -> Option<String> {
45        extract_json_field(json, self.timezone)
46    }
47}
48
49fn extract_json_field(json: &Value, field: Option<&str>) -> Option<String> {
50    if let Some(name) = field
51        && let Some(value) = json.pointer(name).map(|v| v.as_str())
52    {
53        return value.map(std::string::ToString::to_string);
54    }
55
56    None
57}