88 lines
2.0 KiB
Rust
88 lines
2.0 KiB
Rust
use std::str::FromStr;
|
|
|
|
use crate::domain;
|
|
|
|
use super::types::QueryParams;
|
|
|
|
#[derive(Debug, Default, Clone)]
|
|
pub struct Context {
|
|
lang: Option<String>,
|
|
}
|
|
|
|
impl<'a> From<&QueryParams<'a>> for Context {
|
|
fn from(params: &QueryParams<'a>) -> Self {
|
|
params.iter().fold(Context::default(), |mut opts, p| {
|
|
match p {
|
|
("lang", val) => opts.lang = Some(String::from(*val)),
|
|
_ => {}
|
|
};
|
|
|
|
opts
|
|
})
|
|
}
|
|
}
|
|
|
|
impl From<Context> for domain::Context {
|
|
fn from(rest: Context) -> Self {
|
|
Self {
|
|
lang: rest
|
|
.lang
|
|
.and_then(|l| domain::Lang::from_str(&l).ok())
|
|
.unwrap_or_default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn should_create_default_context() {
|
|
let query_params = vec![];
|
|
let rest_ctx = Context::from(&query_params);
|
|
|
|
assert_eq!(rest_ctx.lang, None);
|
|
}
|
|
|
|
#[test]
|
|
fn should_get_lang_from_query_params() {
|
|
let query_params = vec![("lang", "rus")];
|
|
let rest_ctx = Context::from(&query_params);
|
|
|
|
assert_eq!(rest_ctx.lang, Some(String::from("rus")));
|
|
}
|
|
|
|
#[test]
|
|
fn should_create_domain_context_from_rest() {
|
|
let rest_ctx = Context {
|
|
lang: Some(String::from("rus")),
|
|
};
|
|
let ctx = domain::Context::from(rest_ctx);
|
|
|
|
assert_eq!(ctx.lang, domain::Lang::Rus);
|
|
|
|
let rest_ctx = Context {
|
|
lang: Some(String::from("eng")),
|
|
};
|
|
let ctx = domain::Context::from(rest_ctx);
|
|
|
|
assert_eq!(ctx.lang, domain::Lang::Eng);
|
|
}
|
|
|
|
#[test]
|
|
fn should_fallback_lang_to_default_if_lang_unsupported_or_missed() {
|
|
let rest_ctx = Context::default();
|
|
let ctx = domain::Context::from(rest_ctx);
|
|
|
|
assert_eq!(ctx.lang, domain::Lang::Rus);
|
|
|
|
let rest_ctx = Context {
|
|
lang: Some(String::from("unsupported")),
|
|
};
|
|
let ctx = domain::Context::from(rest_ctx);
|
|
|
|
assert_eq!(ctx.lang, domain::Lang::Rus);
|
|
}
|
|
}
|