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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
//! The response handle returned by every endpoint method.
use serde::de::DeserializeOwned;
use crate::error::{Error, Result};
use crate::ratelimit::RateLimitInfo;
/// A completed HTTP response from the Ensembl REST API.
///
/// Endpoint methods return this rather than a deserialized value, so the same
/// call site works for JSON and for the text formats Ensembl serves
/// (`text/x-fasta`, `text/x-gff3`, `text/x-phyloxml`, `text/x-nh`).
///
/// # Examples
///
/// ```no_run
/// # use ensemblrest::{Client, types::LookupRecord};
/// # fn main() -> ensemblrest::Result<()> {
/// let client = Client::new()?;
/// let record: LookupRecord = client.get_lookup_by_id("ENSG00000157764", &[])?.json()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct Response {
status: u16,
content_type: Option<String>,
rate_limit: RateLimitInfo,
body: Vec<u8>,
}
impl Response {
pub(crate) fn new(
status: u16,
content_type: Option<String>,
rate_limit: RateLimitInfo,
body: Vec<u8>,
) -> Self {
Self {
status,
content_type,
rate_limit,
body,
}
}
/// The HTTP status code. Always in the 2xx range for a successful call.
pub fn status(&self) -> u16 {
self.status
}
/// The `Content-Type` header, if the server sent one.
pub fn content_type(&self) -> Option<&str> {
self.content_type.as_deref()
}
/// Rate-limit telemetry parsed from **this response's own headers**.
///
/// A field the server omitted on this response is `None`; it does not
/// inherit a value from an earlier response, and no other thread sharing
/// the [`Client`](crate::Client) can write into it. For the running,
/// sticky, client-wide view — where the last value seen for each field
/// persists — use [`Client::rate_limit`](crate::Client::rate_limit).
pub fn rate_limit(&self) -> &RateLimitInfo {
&self.rate_limit
}
/// The raw response body.
pub fn bytes(&self) -> &[u8] {
&self.body
}
/// Consumes the response, returning the raw body.
pub fn into_bytes(self) -> Vec<u8> {
self.body
}
/// Decodes the body as UTF-8 text.
///
/// Use this for `text/x-fasta`, `text/x-gff3` and the other non-JSON formats.
pub fn text(&self) -> Result<String> {
String::from_utf8(self.body.clone()).map_err(Error::InvalidUtf8)
}
/// Deserializes the body as JSON.
///
/// `T` may be one of the models in [`crate::types`], your own type, or
/// [`serde_json::Value`] when you have no model.
pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
serde_json::from_slice(&self.body).map_err(Error::Decode)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
fn resp(body: &[u8]) -> Response {
Response::new(
200,
Some("application/json".to_string()),
RateLimitInfo::default(),
body.to_vec(),
)
}
#[derive(Debug, Deserialize, PartialEq)]
struct Ping {
ping: i64,
}
#[test]
fn json_deserializes_into_a_struct() {
assert_eq!(
resp(br#"{"ping":1}"#).json::<Ping>().unwrap(),
Ping { ping: 1 }
);
}
#[test]
fn json_deserializes_into_a_value_without_a_model() {
let v: serde_json::Value = resp(br#"{"a":[1,2]}"#).json().unwrap();
assert_eq!(v["a"][1], 2);
}
#[test]
fn json_on_malformed_body_is_a_decode_error() {
let err = resp(b"not json").json::<Ping>().unwrap_err();
assert!(matches!(err, Error::Decode(_)), "got {err:?}");
}
#[test]
fn text_returns_non_json_payloads() {
// The FASTA path: this is why Response exists rather than a generic return.
let fasta = b">ENSG00000157764\nACGT\n";
assert_eq!(resp(fasta).text().unwrap(), ">ENSG00000157764\nACGT\n");
}
#[test]
fn text_on_invalid_utf8_is_an_error_not_a_panic() {
let err = resp(&[0xFF, 0xFE]).text().unwrap_err();
assert!(matches!(err, Error::InvalidUtf8(_)), "got {err:?}");
}
#[test]
fn bytes_and_into_bytes_expose_the_raw_body() {
let r = resp(b"\x00\x01\x02");
assert_eq!(r.bytes(), &[0, 1, 2]);
assert_eq!(r.into_bytes(), vec![0, 1, 2]);
}
#[test]
fn metadata_accessors_report_what_was_constructed() {
let rate = RateLimitInfo {
remaining: Some(7),
..Default::default()
};
let r = Response::new(404, Some("text/plain".into()), rate, Vec::new());
assert_eq!(r.status(), 404);
assert_eq!(r.content_type(), Some("text/plain"));
assert_eq!(r.rate_limit().remaining, Some(7));
}
}