Skip to main content

wikibase_rest_api/
header_info.rs

1#[derive(Debug, Clone, Default, PartialEq, Copy)]
2pub struct HeaderInfo {
3    revision_id: Option<u64>,
4    last_modified: Option<chrono::DateTime<chrono::Utc>>,
5}
6
7impl HeaderInfo {
8    /// Constructs a new `HeaderInfo` object from a `HeaderMap` (from a `reqwest::Response`).
9    pub fn from_header(header: &reqwest::header::HeaderMap) -> Self {
10        let revision_id = header
11            .get("ETag")
12            .and_then(|v| v.to_str().ok())
13            .and_then(|s| s.replace('"', "").parse::<u64>().ok());
14        let last_modified = header
15            .get("Last-Modified")
16            .and_then(|v| v.to_str().ok())
17            .and_then(|s| chrono::DateTime::parse_from_rfc2822(s).ok())
18            .map(|dt| dt.to_utc());
19        Self {
20            revision_id,
21            last_modified,
22        }
23    }
24
25    /// Returns the revision ID.
26    pub const fn revision_id(&self) -> Option<u64> {
27        self.revision_id
28    }
29
30    /// Returns the last modified date.
31    pub const fn last_modified(&self) -> Option<&chrono::DateTime<chrono::Utc>> {
32        self.last_modified.as_ref()
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39    use http::HeaderValue;
40    use reqwest::header::HeaderMap;
41
42    #[test]
43    fn test_header_info() {
44        let mut headers = HeaderMap::new();
45        headers.insert("ETag", HeaderValue::from_str("1234567890").unwrap());
46        headers.insert(
47            "Last-Modified",
48            HeaderValue::from_str("Wed, 21 Oct 2015 07:28:00 GMT").unwrap(),
49        );
50        let hi = HeaderInfo::from_header(&headers);
51        assert_eq!(hi.revision_id(), Some(1234567890));
52        assert_eq!(
53            hi.last_modified().unwrap().to_rfc2822(),
54            "Wed, 21 Oct 2015 07:28:00 +0000"
55        );
56    }
57}