1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
9pub struct IntakeRequest<T> {
10 path: String,
11 headers: BTreeMap<String, String>,
12 items: T,
13}
14
15impl<T> IntakeRequest<T> {
16 pub fn new<'a, I>(path: impl Into<String>, headers: I, items: T) -> Self
20 where
21 I: IntoIterator<Item = (&'a str, &'a str)>,
22 {
23 let mut header_map = BTreeMap::<String, String>::new();
24 for (name, value) in headers {
25 header_map
26 .entry(name.to_ascii_lowercase())
27 .and_modify(|existing| {
28 existing.push_str(", ");
29 existing.push_str(value);
30 })
31 .or_insert_with(|| value.to_string());
32 }
33
34 Self {
35 path: path.into(),
36 headers: header_map,
37 items,
38 }
39 }
40
41 pub fn path(&self) -> &str {
43 &self.path
44 }
45
46 pub fn headers(&self) -> &BTreeMap<String, String> {
48 &self.headers
49 }
50
51 pub fn header(&self, name: &str) -> Option<&str> {
53 self.headers.get(&name.to_ascii_lowercase()).map(String::as_str)
54 }
55
56 pub fn items(&self) -> &T {
58 &self.items
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::IntakeRequest;
65
66 #[test]
67 fn headers_are_lowercased_and_repeated_values_joined() {
68 let request = IntakeRequest::new(
69 "/api/v2/series",
70 [("User-Agent", "agent/1.0"), ("X-Tag", "a"), ("x-tag", "b")],
71 Vec::<u32>::new(),
72 );
73
74 assert_eq!(request.path(), "/api/v2/series");
75 assert_eq!(request.header("USER-AGENT"), Some("agent/1.0"));
76 assert_eq!(request.header("x-tag"), Some("a, b"));
77 assert_eq!(request.header("missing"), None);
78 assert_eq!(request.headers().len(), 2);
79 }
80}