odata-simple-client 0.2.6

Simplified OpenData API Client
Documentation
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! This crate provides a Rust-interface to an [OData 3.0](https://www.odata.org/documentation/odata-version-3-0/) API over HTTP(S)
//!
//! To get started, construct a [`DataSource`] and then create either a [`ListRequest`] or [`GetRequest`] and
//! [`fetch`](`DataSource::fetch`)/[`fetch_paged`](`DataSource::fetch_paged`) it using your [`DataSource`]
//!
//! Here's a complete example which fetches a single `Dokument` from the [Danish Parliament's](https://oda.ft.dk) OData API:
//!
//!  ```rust
//! use hyper::{Client, client::HttpConnector};
//! use hyper_openssl::{HttpsConnector};
//! use odata_simple_client::{DataSource, GetRequest};
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Dokument {
//!     titel: String,
//! }
//!
//! // Construct a Hyper client for communicating over HTTPS
//! let client: Client<HttpsConnector<HttpConnector>> =
//!     Client::builder().build(HttpsConnector::<HttpConnector>::new().unwrap());
//!
//! // Set up our DataSource. The API is reachable on https://oda.ft.dk/api/
//! let datasource = DataSource::new(client, "oda.ft.dk", Some(String::from("/api"))).unwrap();
//!
//! // The tokio_test::block_on call is just to make this example work in a rustdoc example.
//! // Normally you would just write the enclosed code in an async function.
//! tokio_test::block_on(async {
//!     let dokument: Dokument = datasource.fetch(
//!         GetRequest::new("Dokument", 24)
//!      ).await.unwrap();
//!
//!     assert_eq!(dokument.titel, "Grund- og nærhedsnotat vedr. sanktioner på toldområdet");
//! });
//!  ```
//! The example above has requirements on a number of crates. See the `Cargo.toml`-file for a list.

#![deny(
    bad_style,
    dead_code,
    improper_ctypes,
    non_shorthand_field_patterns,
    no_mangle_generic_items,
    overflowing_literals,
    path_statements,
    patterns_in_fns_without_body,
    private_in_public,
    unconditional_recursion,
    unused,
    unused_allocation,
    unused_comparisons,
    unused_parens,
    while_true,
    missing_debug_implementations,
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results
)]
#![forbid(unsafe_code)]

#[cfg(feature = "rate-limiting")]
mod ratelimiting;
#[cfg(feature = "rate-limiting")]
pub use ratelimiting::RateLimitedDataSource;

mod path;
use path::PathBuilder;
pub use path::{Comparison, Direction, Format, InlineCount};

use hyper::{
    body::Buf,
    client::{connect::Connect, Client},
    http::uri::{Authority, InvalidUri, Scheme},
    Body, Response, Uri,
};
use log::debug;
use serde::{de::DeserializeOwned, Deserialize};
use std::{convert::TryFrom, io::Read};
use thiserror::Error;

/// Umbrella trait covering all the traits required of a [`Client`] for a [`DataSource`] to work.
pub trait Connector: Connect + Clone + Send + Sync + 'static {}
impl<T: Connect + Clone + Send + Sync + 'static> Connector for T {}

/// Represents a target OData API.
#[derive(Clone, Debug)]
pub struct DataSource<C> {
    client: Client<C>,
    authority: Authority,
    base_path: String,
    scheme: Scheme,
}

/// Generalized Error type encompassing all the possible errors that can be generated by this crate.
#[derive(Error, Debug)]
pub enum Error {
    /// The provided URI was not valid.
    #[error("invalid URI")]
    Uri(#[from] InvalidUri),
    /// HTTP error occurred while executing a request.
    #[error("http error")]
    Http(#[from] hyper::http::Error),
    /// A Hyper error occurred while executing the request, or constructing the Client.
    #[error("hyper error")]
    Hyper(#[from] hyper::Error),
    /// An error occurred while serializing or deserializing data during a request or response.
    #[error("serde error")]
    Serde(serde_json::Error, String),
    /// An IO error occurred.
    #[error("io error")]
    Io(#[from] std::io::Error),
}

/// Wraps lists of Resources returned by the API. Used for deserializing ListRequest responses.
#[derive(Debug, Deserialize)]
pub struct Page<T> {
    /// List of returned values in the page.
    pub value: Vec<T>,
    #[serde(rename = "odata.count")]
    /// Inline count of remanining objects to be fetched, excluding the ones in this page.
    pub count: Option<String>,
    /// URL Request to send, to fetch the next page in this sequence.
    #[serde(rename = "odata.nextLink")]
    pub next_link: Option<String>,
    /// Url to the schema describing the data returned
    #[serde(rename = "odata.metadata")]
    pub metadata: Option<String>,
}

async fn deserialize_as<T: DeserializeOwned>(response: Response<Body>) -> Result<T, Error> {
    let body = hyper::body::aggregate(response).await?;

    let mut content = String::new();
    // We don't care about the read number of bytes,
    // we just read until EOF.
    let _ = body.reader().read_to_string(&mut content)?;

    serde_json::from_str(&content).map_err(|e| Error::Serde(e, content))
}

impl<C> DataSource<C>
where
    C: Connector,
{
    /// Construct a new DataSource using a [`Client`], [`Authority`] and a base_domain.
    /// ```rust
    /// # use hyper::{Client, client::HttpConnector};
    /// # use hyper_openssl::{HttpsConnector};
    /// # use odata_simple_client::DataSource;
    /// # let client: Client<HttpsConnector<HttpConnector>> =
    /// #   Client::builder().build(HttpsConnector::<HttpConnector>::new().unwrap());
    /// #
    /// let datasource = DataSource::new(
    ///     client,
    ///     "oda.ft.dk",
    ///     Some(String::from("/api"))
    /// ).unwrap();
    /// ```
    pub fn new<A>(
        client: Client<C>,
        domain: A,
        base_path: Option<String>,
    ) -> Result<DataSource<C>, Error>
    where
        Authority: TryFrom<A>,
        Error: From<<Authority as TryFrom<A>>::Error>,
    {
        Ok(DataSource {
            client,
            authority: Authority::try_from(domain)?,
            base_path: base_path.unwrap_or_default(),
            scheme: Scheme::HTTPS,
        })
    }

    async fn execute<R>(&self, request: R) -> Result<Response<Body>, Error>
    where
        R: Into<PathBuilder>,
    {
        let builder: PathBuilder = request.into().base_path(self.base_path.clone());

        let uri = Uri::builder()
            .scheme(self.scheme.as_ref())
            .authority(self.authority.as_ref())
            .path_and_query(builder.build()?)
            .build()?;

        debug!("fetching {}", uri);
        Ok(self.client.get(uri).await?)
    }

    /// Fetch a single resource using a [`GetRequest`]
    /// ```rust
    /// # use hyper::{Client, client::HttpConnector};
    /// # use hyper_openssl::{HttpsConnector};
    /// # use odata_simple_client::{DataSource, GetRequest};
    /// # use serde::Deserialize;
    /// #
    /// # let client: Client<HttpsConnector<HttpConnector>> =
    /// #   Client::builder().build(HttpsConnector::<HttpConnector>::new().unwrap());
    /// #
    /// # let datasource = DataSource::new(client, "oda.ft.dk", Some(String::from("/api"))).unwrap();
    /// #
    /// #[derive(Deserialize)]
    /// struct Dokument {
    ///     titel: String,
    /// }
    ///
    /// # tokio_test::block_on(async {
    /// let dokument: Dokument = datasource.fetch(
    ///         GetRequest::new("Dokument", 24)
    ///     ).await.unwrap();
    ///
    /// assert_eq!(dokument.titel, "Grund- og nærhedsnotat vedr. sanktioner på toldområdet");
    /// # });
    /// ```
    pub async fn fetch<T>(&self, request: GetRequest) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let response = self
            .execute(Into::<PathBuilder>::into(request).format(Format::Json))
            .await?;
        deserialize_as::<T>(response).await
    }

    /// Fetch a [`Page`]d list of resources using a [`ListRequest`]
    /// ```rust
    /// # use hyper::{Client, client::HttpConnector};
    /// # use hyper_openssl::{HttpsConnector};
    /// # use odata_simple_client::{DataSource, ListRequest, Page, InlineCount};
    /// # use serde::Deserialize;
    /// #
    /// # let client: Client<HttpsConnector<HttpConnector>> =
    /// #   Client::builder().build(HttpsConnector::<HttpConnector>::new().unwrap());
    /// #
    /// # let datasource = DataSource::new(client, "oda.ft.dk", Some(String::from("/api"))).unwrap();
    /// #
    /// #[derive(Deserialize)]
    /// struct Dokument {
    ///     titel: String,
    /// }
    ///
    /// # tokio_test::block_on(async {
    /// let page: Page<Dokument> = datasource
    ///     .fetch_paged(ListRequest::new("Dokument")
    ///         .inline_count(InlineCount::AllPages)
    ///     ).await.unwrap();
    /// assert!(page.count.unwrap().parse::<u32>().unwrap() > 0)
    /// # });
    /// ```
    pub async fn fetch_paged<T>(&self, request: ListRequest) -> Result<Page<T>, Error>
    where
        T: DeserializeOwned,
    {
        let response = self
            .execute(Into::<PathBuilder>::into(request).format(Format::Json))
            .await?;
        deserialize_as::<Page<T>>(response).await
    }
}

/// Request a single resource by ID
#[derive(Debug, Clone)]
pub struct GetRequest {
    builder: PathBuilder,
}

impl GetRequest {
    /// Constructs a GET request for `<DataSource Path>/resource_type(id)`
    ///
    /// Must be [`DataSource::fetch`]ed using a [`DataSource`] to retrieve data.
    pub fn new(resource_type: &str, id: usize) -> Self {
        GetRequest {
            builder: PathBuilder::new(resource_type.to_string()).id(id),
        }
    }

    /// Change format of the returned data.
    ///
    /// Can be either [`Format::Json`] or [`Format::Xml`]
    pub fn format(mut self, format: Format) -> Self {
        self.builder = self.builder.format(format);
        self
    }

    /// Expand specific relations of the returned object, if possible.
    ///
    /// For the [Folketinget API](https://oda.ft.dk) for example, you can expand the `DokumentAktør` field of a `Dokument`, to simultaneously retrieve information about the document authors, instead of having to do two separate lookups for the `DokumentAktør` relation and then the actual `Aktør`.
    pub fn expand<'f, F>(mut self, field: F) -> Self
    where
        F: IntoIterator<Item = &'f str>,
    {
        self.builder = self.builder.expand(field);
        self
    }
}

impl From<GetRequest> for PathBuilder {
    fn from(request: GetRequest) -> Self {
        request.builder
    }
}

/// Request a list of resources.
#[derive(Debug, Clone)]
pub struct ListRequest {
    builder: PathBuilder,
}

impl ListRequest {
    /// Create a new ListRequest, fetching all resources of type `resource_type`.
    ///
    /// Use a [`DataSource`] to execute the `ListRequest`
    pub fn new(resource_type: &str) -> Self {
        ListRequest {
            builder: PathBuilder::new(resource_type.to_string()),
        }
    }

    /// Change format of the returned data.
    ///
    /// Can be either [`Format::Json`] or [`Format::Xml`]
    pub fn format(mut self, format: Format) -> Self {
        self.builder = self.builder.format(format);
        self
    }

    /// Order the returned resources by `field`, in specified `direction`. [`Direction::Ascending`] by default.
    pub fn order_by(mut self, field: &str, direction: Direction) -> Self {
        self.builder = self.builder.order_by(field, direction);
        self
    }

    /// Only retrieve the top `count` items.
    pub fn top(mut self, count: u32) -> Self {
        self.builder = self.builder.top(count);
        self
    }

    /// Skip the first `count` items.
    pub fn skip(mut self, count: u32) -> Self {
        self.builder = self.builder.skip(count);
        self
    }

    /// Include an inline count field in the odata page metadata.
    /// Useful for gauging how many results/pages are left. By default this is not specified, which implies [`InlineCount::None`]
    pub fn inline_count(mut self, value: InlineCount) -> Self {
        self.builder = self.builder.inline_count(value);
        self
    }

    /// Filter the returned results using an OData conditional expression.
    ///
    /// See [the OData 2.0 documentation (section 4.5)](https://www.odata.org/documentation/odata-version-2-0/uri-conventions/) for more information.
    /// ```rust
    /// # use hyper::{Client, client::HttpConnector};
    /// # use hyper_openssl::{HttpsConnector};
    /// # use odata_simple_client::{DataSource, ListRequest, Page, Comparison};
    /// # use serde::Deserialize;
    /// #
    /// # let client: Client<HttpsConnector<HttpConnector>> =
    /// #   Client::builder().build(HttpsConnector::<HttpConnector>::new().unwrap());
    /// #
    /// # let datasource = DataSource::new(client, "oda.ft.dk", Some(String::from("/api"))).unwrap();
    /// #
    /// #[derive(Deserialize, Debug)]
    /// struct Dokument {
    ///     titel: String,
    /// }
    ///
    /// # tokio_test::block_on(async {
    /// let page: Page<Dokument> = datasource
    ///     .fetch_paged(ListRequest::new("Dokument")
    ///         .filter("id", Comparison::Equal, "24")
    ///     ).await.unwrap();
    /// assert_eq!(page.value[0].titel, "Grund- og nærhedsnotat vedr. sanktioner på toldområdet")
    /// # });
    /// ```
    pub fn filter(mut self, field: &str, comparison: Comparison, value: &str) -> Self {
        self.builder = self.builder.filter(field, comparison, value);
        self
    }

    /// Expand specific relations of the returned object, if possible.
    ///
    /// For the [Folketinget API](https://oda.ft.dk) for example, you can expand the `DokumentAktør` field of a `Dokument`, to simultaneously retrieve information about the document authors, instead of having to do two separate lookups for the `DokumentAktør` relation and then the actual `Aktør`.
    pub fn expand<'f, F>(mut self, field: F) -> Self
    where
        F: IntoIterator<Item = &'f str>,
    {
        self.builder = self.builder.expand(field);
        self
    }
}

impl From<ListRequest> for PathBuilder {
    fn from(request: ListRequest) -> Self {
        request.builder
    }
}