|
| 1 | +//! Service info configuration. |
| 2 | +//! |
| 3 | +
|
| 4 | +use serde::de::Error; |
| 5 | +use serde::{Deserialize, Deserializer, Serialize}; |
| 6 | +use serde_json::Value; |
| 7 | +use std::collections::HashMap; |
| 8 | + |
| 9 | +/// Service info config. |
| 10 | +#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)] |
| 11 | +#[serde(default)] |
| 12 | +pub struct ServiceInfo(HashMap<String, Value>); |
| 13 | + |
| 14 | +impl ServiceInfo { |
| 15 | + /// Create a service info. |
| 16 | + pub fn new(fields: HashMap<String, Value>) -> Self { |
| 17 | + Self(fields) |
| 18 | + } |
| 19 | + |
| 20 | + /// Get the inner value. |
| 21 | + pub fn into_inner(self) -> HashMap<String, Value> { |
| 22 | + self.0 |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl AsRef<HashMap<String, Value>> for ServiceInfo { |
| 27 | + fn as_ref(&self) -> &HashMap<String, Value> { |
| 28 | + &self.0 |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl<'de> Deserialize<'de> for ServiceInfo { |
| 33 | + fn deserialize<D>(deserializer: D) -> Result<ServiceInfo, D::Error> |
| 34 | + where |
| 35 | + D: Deserializer<'de>, |
| 36 | + { |
| 37 | + let fields: HashMap<String, Value> = HashMap::<String, Value>::deserialize(deserializer)? |
| 38 | + .into_iter() |
| 39 | + .map(|(key, value)| (key.to_lowercase(), value)) |
| 40 | + .collect(); |
| 41 | + |
| 42 | + let err_msg = |invalid_key| format!("reserved service info field `{}`", invalid_key); |
| 43 | + |
| 44 | + if fields.contains_key("type") { |
| 45 | + return Err(Error::custom(err_msg("type"))); |
| 46 | + } |
| 47 | + |
| 48 | + if fields.contains_key("htsget") { |
| 49 | + return Err(Error::custom(err_msg("htsget"))); |
| 50 | + } |
| 51 | + |
| 52 | + Ok(ServiceInfo::new(fields)) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +#[cfg(test)] |
| 57 | +mod tests { |
| 58 | + use super::*; |
| 59 | + use crate::config::tests::test_serialize_and_deserialize; |
| 60 | + use crate::config::Config; |
| 61 | + use serde_json::json; |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn service_info() { |
| 65 | + test_serialize_and_deserialize( |
| 66 | + r#" |
| 67 | + service_info.environment = "dev" |
| 68 | + service_info.organization = { name = "name", url = "https://example.com/" } |
| 69 | + "#, |
| 70 | + HashMap::from_iter(vec![ |
| 71 | + ("environment".to_string(), json!("dev")), |
| 72 | + ( |
| 73 | + "organization".to_string(), |
| 74 | + json!({ "name": "name", "url": "https://example.com/" }), |
| 75 | + ), |
| 76 | + ]), |
| 77 | + |result: Config| result.service_info.0, |
| 78 | + ); |
| 79 | + } |
| 80 | +} |
0 commit comments