1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use noodles_core::region::Interval;

use crate::{Client, Error, Sequence};

/// A sequence endpoint builder.
pub struct Builder {
    client: Client,
    id: String,
    interval: Option<Interval>,
}

impl Builder {
    pub(crate) fn new<I>(client: Client, id: I) -> Self
    where
        I: Into<String>,
    {
        Self {
            client,
            id: id.into(),
            interval: None,
        }
    }

    /// Sets the interval to query.
    pub fn set_interval<I>(mut self, interval: I) -> Self
    where
        I: Into<Interval>,
    {
        self.interval = Some(interval.into());
        self
    }

    /// Sends the request.
    pub async fn send(self) -> crate::Result<Sequence> {
        let endpoint = self
            .client
            .base_url()
            .join(&format!("sequence/{}", self.id))
            .map_err(Error::Url)?;

        let mut request = self.client.http_client().get(endpoint);

        if let Some(interval) = self.interval {
            let mut query = Vec::new();

            let (resolved_start, resolved_end) = resolve_interval(interval);

            if let Some(start) = resolved_start {
                query.push(("start", start.to_string()));
            }

            if let Some(end) = resolved_end {
                query.push(("end", end.to_string()));
            }

            request = request.query(&query);
        }

        let response = request.send().await.map_err(Error::Request)?;
        let sequence = response.bytes().await.map_err(Error::Request)?;

        Ok(Sequence::new(self.client, self.id, sequence))
    }
}

fn resolve_interval<I>(interval: I) -> (Option<usize>, Option<usize>)
where
    I: Into<Interval>,
{
    let interval = interval.into();
    let start = interval.start().map(|position| usize::from(position) - 1);
    let end = interval.end().map(usize::from);
    (start, end)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_resolve_interval() -> std::result::Result<(), noodles_core::position::TryFromIntError> {
        use noodles_core::Position;

        let start = Position::try_from(8)?;
        let end = Position::try_from(13)?;

        assert_eq!(resolve_interval(start..=end), (Some(7), Some(13)));
        assert_eq!(resolve_interval(start..), (Some(7), None));
        assert_eq!(resolve_interval(..=end), (None, Some(13)));
        assert_eq!(resolve_interval(..), (None, None));

        Ok(())
    }
}