crossref/lib.rs
1//! This crate provides a client for interacting with the crossref-api
2//!
3//! [Crossref API docs](https://github.com/CrossRef/rest-api-doc)
4//! `Crossref` - Crossref search API. The `Crossref` crate provides methods matching Crossref API routes:
5
6//! * `works` - `/works` route
7//! * `members` - `/members` route
8//! * `prefixes` - `/prefixes` route
9//! * `funders` - `/funders` route
10//! * `journals` - `/journals` route
11//! * `types` - `/types` route
12//! * `agency` - `/works/{doi}/agency` get DOI minting agency
13//!
14//! ## Usage
15
16//! ### Create a `Crossref` client:
17
18//! ```edition2018
19//! # use crossref::Crossref;
20//! # fn run() -> Result<(), crossref::Error> {
21//! let client = Crossref::builder().build()?;
22//! # Ok(())
23//! # }
24//! ```
25//!
26//! If you have an [Authorization token for Crossref's Plus service](https://github.com/CrossRef/rest-api-doc#authorization-token-for-plus-service):
27//!
28//! ```edition2018
29//! # use crossref::Crossref;
30//! # fn run() -> Result<(), crossref::Error> {
31//! let client = Crossref::builder()
32//! .token("token")
33//! .build()?;
34//! # Ok(())
35//! # }
36//! ```
37//!
38//! Encouraged to use the **The Polite Pool**:
39//!
40//! [Good manners = more reliable service](https://github.com/CrossRef/rest-api-doc#good-manners--more-reliable-service)
41//!
42//! To get into Crossref's polite pool include a email address
43//!
44//! ```edition2018
45//! # use crossref::Crossref;
46//! # fn run() -> Result<(), crossref::Error> {
47//! let client = Crossref::builder()
48//! .polite("polite@example.com")
49//! .token("your token")
50//! .build()?;
51//! # Ok(())
52//! # }
53//! ```
54//!
55//! ### Constructing Queries
56//! Not all components support queries and there are custom available parameters for each route that supports querying.
57//! For each resource components that supports querying there exist a Query struct: `WorksQuery`, `MembersQuery`, `FundersQuery`. The `WorksQuery` also differs from the others by supporting [deep paging with cursors](https://github.com/CrossRef/rest-api-doc#deep-paging-with-cursors) and [field queries](https://github.com/CrossRef/rest-api-doc#works-field-queries).
58//!
59//! Otherwise creating queries works the same for all resource components:
60//!
61//! ```edition2018
62//! # use crossref::*;
63//! # fn run() -> Result<()> {
64//! let query = WorksQuery::new("Machine Learning")
65//! // field queries supported for `Works`
66//! .field_query(FieldQuery::author("Some Author"))
67//! // filters are specific for each resource component
68//! .filter(WorksFilter::HasOrcid)
69//! .order(Order::Asc)
70//! .sort(Sort::Score);
71//! # Ok(())
72//! # }
73//! ```
74//!
75//!
76//! ### Get Records
77//!
78//! See [this table](https://github.com/CrossRef/rest-api-doc#resource-components) for a detailed overview of the major components.
79//!
80//! There are 3 available targets:
81//!
82//! * **standalone resource components**: `/works`, `/members`, etc. that return a list list of the corresponding items and can be specified with queries
83//! * **Resource component with identifiers**: `/works/{doi}?<query>`,`/members/{member_id}?<query>`, etc. that returns a single item if found.
84//! * **combined with the `works` route**: The works component can be appended to other resources: `/members/{member_id}/works?<query>` etc. that returns a list of matching `Work` items.
85//!
86//! This resembles in the enums of the resource components, eg. for `Members`:
87//!
88//! ```edition2018
89//! # use crossref::query::*;
90//! pub enum Members {
91//! /// target a specific member at `/members/{id}`
92//! Identifier(String),
93//! /// target all members that match the query at `/members?query...`
94//! Query(MembersQuery),
95//! /// target a `Work` for a specific member at `/members/{id}/works?query..`
96//! Works(WorksIdentQuery),
97//! }
98//! ```
99//!
100//! All options are supported by the client:
101//!
102//! **Single Item by DOI (ID)**
103//!
104//! Analogous methods exist for all resource components
105//!
106//! ```edition2018
107//! # use crossref::*;
108//! # async fn run() -> Result<()> {
109//! # let client = Crossref::builder().build()?;
110//! let work = client.work("10.1037/0003-066X.59.1.29").await?;
111//!
112//! let agency = client.work_agency("10.1037/0003-066X.59.1.29").await?;
113//!
114//! let funder = client.funder("funder_id").await?;
115//!
116//! let member = client.member("member_id").await?;
117//! # Ok(())
118//! # }
119//! ```
120//!
121//! **Query**
122//!
123//! ```edition2018
124//! # use crossref::*;
125//! # async fn run() -> Result<()> {
126//! # let client = Crossref::builder().build()?;
127//! let query = WorksQuery::new("Machine Learning");
128//!
129//! // one page of the matching results
130//! let works = client.works(query).await?;
131//! # Ok(())
132//! # }
133//! ```
134//!
135//! Alternatively insert a free form query term directly
136//!
137//! ```edition2018
138//! # use crossref::*;
139//! # async fn run() -> Result<()> {
140//! # let client = Crossref::builder().build()?;
141//!
142//! // one page of the matching results
143//! let works = client.works("Machine Learning").await?;
144//! # Ok(())
145//! # }
146//! ```
147//!
148//! **Combining Routes with the `Works` route**
149//!
150//! For each resource component other than `Works` there exist methods to append a `WorksQuery` with the ID option `/members/{member_id}/works?<query>?`
151//!
152//! ```edition2018
153//! # use crossref::*;
154//! # async fn run() -> Result<()> {
155//! # let client = Crossref::builder().build()?;
156//! let works = client.member_works( WorksQuery::new("machine learning")
157//! .sort(Sort::Score).into_ident("member_id")).await?;
158//! # Ok(())
159//! # }
160//! ```
161//!
162//! This would be the same as using the [`Crossref::works`] method by supplying the combined type
163//!
164//! ```edition2018
165//! # use crossref::*;
166//! # async fn run() -> Result<()> {
167//! # let client = Crossref::builder().build()?;
168//! let works = client.works(WorksQuery::new("machine learning")
169//! .sort(Sort::Score)
170//! .into_combined_query::<Members>("member_id")).await?;
171//! # Ok(())
172//! # }
173//! ```
174//!
175//! ** Deep paging for `Works` **
176//! [Deep paging results](https://github.com/CrossRef/rest-api-doc#deep-paging-with-cursors)
177//! Deep paging is supported for all queries, that return a list of `Work`, `WorkList`.
178//! This function returns a new iterator over pages of `Work`, which is returned as bulk of items as a `WorkList` by crossref.
179//! Usually a single page `WorkList` contains 20 items.
180//!
181//! # Example
182//!
183//! Iterate over all `Works` linked to search term `Machine Learning`
184//!
185//! ```edition2018
186//! use crossref::{Crossref, WorksQuery, Work};
187//! # async fn run() -> Result<(), crossref::Error> {
188//! let client = Crossref::builder().build()?;
189//!
190//! let all_works: Vec<Work> = client.deep_page(WorksQuery::new("Machine Learning")).await.into_iter().flat_map(|x|x.items).collect();
191//!
192//! # Ok(())
193//! # }
194//! ```
195//!
196//!
197//! # Example
198//!
199//! Iterate over all the pages (`WorkList`) of the funder with id `funder id` by using a combined query.
200//! A single `WorkList` usually holds 20 `Work` items.
201//!
202//! ```edition2018
203//! use crossref::{Crossref, Funders, WorksQuery, Work, WorkList};
204//! # async fn run() -> Result<(), crossref::Error> {
205//! let client = Crossref::builder().build()?;
206//!
207//! let all_funder_work_list: Vec<WorkList> = client.deep_page(WorksQuery::default().into_combined_query::<Funders>("funder id")).await;
208//!
209//! # Ok(())
210//! # }
211//! ```
212//! # Example
213//!
214//! Iterate over all `Work` items of a specific funder directly.
215//!
216//! ```edition2018
217//! use crossref::{Crossref, Funders, WorksQuery, Work, WorkList};
218//! # async fn run() -> Result<(), crossref::Error> {
219//! let client = Crossref::builder().build()?;
220//!
221//! let all_works: Vec<Work> = client.deep_page(WorksQuery::default()
222//! .into_combined_query::<Funders>("funder id")).await
223//! .into_iter()
224//! .flat_map(|x| x.items)
225//! .collect();
226//!
227//! # Ok(())
228//! # }
229//! ```
230
231#![deny(warnings)]
232#![deny(missing_docs)]
233
234mod error;
235/// provides types to construct a specific query
236pub mod query;
237/// provides the response types of the crossref api
238pub mod response;
239
240// TODO extract to optional feature?
241/// content negotiation
242pub mod cn;
243/// textual data mining
244pub mod tdm;
245
246#[doc(inline)]
247pub use self::error::{Error, Result};
248
249#[doc(inline)]
250pub use self::query::works::{
251 FieldQuery, WorkListQuery, WorkResultControl, Works, WorksFilter, WorksIdentQuery, WorksQuery,
252};
253
254#[doc(inline)]
255pub use self::query::{Component, CrossrefQuery, CrossrefRoute, Order, Sort};
256pub use self::query::{Funders, Journals, Members, Prefixes, Type, Types};
257pub use self::response::{
258 CrossrefType, Funder, FunderList, Journal, JournalList, Member, MemberList, TypeList, Work,
259 WorkAgency, WorkList,
260};
261
262pub(crate) use self::response::{Message, Response};
263
264use crate::query::{FundersQuery, MembersQuery};
265use crate::response::{MessageType, Prefix};
266use reqwest::{self, Client};
267
268macro_rules! get_item {
269 ($ident:ident, $value:expr, $got:expr) => {
270 if let Some(msg) = $value {
271 match msg {
272 Message::$ident(item) => Ok(item),
273 _ => Err(Error::UnexpectedItem {
274 expected: MessageType::$ident,
275 got: $got,
276 }),
277 }
278 } else {
279 Err(Error::MissingMessage {
280 expected: MessageType::$ident,
281 })
282 }
283 };
284}
285
286macro_rules! impl_combined_works_query {
287 ($($name:ident $component:ident,)*) => {
288 $(
289 /// Return one page of the components's `Work` that match the query
290 ///
291 pub async fn $name(&self, ident: WorksIdentQuery) -> Result<WorkList> {
292 let resp = self.get_response(&$component::Works(ident)).await?;
293 get_item!(WorkList, resp.message, resp.message_type)
294 })+
295 };
296}
297
298/// Struct for Crossref search API methods
299#[derive(Debug, Clone)]
300pub struct Crossref {
301 /// use another base url than `api.crossref.org`
302 pub base_url: String,
303 /// the reqwest client that handles the requests
304 pub http_client: Client,
305}
306
307impl Crossref {
308 const BASE_URL: &'static str = "https://api.crossref.org";
309
310 /// Constructs a new `CrossrefBuilder`.
311 ///
312 /// This is the same as `Crossref::builder()`.
313 pub fn builder() -> CrossrefBuilder {
314 CrossrefBuilder::new()
315 }
316
317 // generate all functions to query combined endpoints
318 impl_combined_works_query!(funder_works Funders, member_works Members,
319 type_works Types, journal_works Journals, prefix_works Prefixes,);
320
321 /// Transforms the `CrossrefQuery` in the request route and executes the request
322 ///
323 /// # Errors
324 ///
325 /// If it was a bad url, the server will return `Resource not found` a `ResourceNotFound` error will be returned in this case
326 /// Also fails if the json response body could be parsed into `Response`
327 /// Fails if there was an error in reqwest executing the request [::reqwest::RequestBuilder::send]
328 async fn get_response<T: CrossrefQuery>(&self, query: &T) -> Result<Response> {
329 let url = query.to_url(&self.base_url)?;
330 let resp = self.http_client.get(&url).send().await?.text().await?;
331 if resp.starts_with("Resource not found") {
332 Err(Error::ResourceNotFound {
333 resource: Box::new(query.clone().resource_component()),
334 })
335 } else {
336 Ok(serde_json::from_str(&resp)?)
337 }
338 }
339
340 /// Return the `Work` items that match a certain query.
341 ///
342 /// To search only by query terms use the convenience query method [Crossref::query_works]
343 ///
344 /// # Example
345 ///
346 /// ```edition2018
347 /// use crossref::{Crossref, WorksQuery, WorksFilter, FieldQuery};
348 /// # async fn run() -> Result<(), crossref::Error> {
349 /// let client = Crossref::builder().build()?;
350 ///
351 /// let query = WorksQuery::new("Machine Learning")
352 /// .filter(WorksFilter::HasOrcid)
353 /// .order(crossref::Order::Asc)
354 /// .field_query(FieldQuery::author("Some Author"))
355 /// .sort(crossref::Sort::Score);
356 ///
357 /// let works = client.works(query).await?;
358 ///
359 /// # Ok(())
360 /// # }
361 /// ```
362 ///
363 /// # Errors
364 ///
365 /// This method fails if the `works` element expands to a bad route `ResourceNotFound`
366 /// Fails if the response body doesn't have `message` field `MissingMessage`.
367 /// Fails if anything else than a `WorkList` is returned as message `UnexpectedItem`
368 pub async fn works<T: Into<WorkListQuery>>(&self, query: T) -> Result<WorkList> {
369 let resp = self.get_response(&query.into()).await?;
370 get_item!(WorkList, resp.message, resp.message_type)
371 }
372
373 /// Return the `Work` that is identified by the `doi`.
374 ///
375 /// # Errors
376 /// This method fails if the doi could not identified `ResourceNotFound`
377 ///
378 pub async fn work(&self, doi: &str) -> Result<Work> {
379 let resp = self
380 .get_response(&Works::Identifier(doi.to_string()))
381 .await?;
382 get_item!(Work, resp.message, resp.message_type).map(|x| *x)
383 }
384
385 /// [Deep paging results](https://github.com/CrossRef/rest-api-doc#deep-paging-with-cursors)
386 /// Deep paging is supported for all queries, that return a list of `Work`, `WorkList`.
387 /// This function returns a new iterator over pages of `Work`, which is returned as bulk of items as a `WorkList` by crossref.
388 /// Usually a single page `WorkList` contains 20 items.
389 ///
390 /// # Example
391 ///
392 /// Iterate over all `Works` linked to search term `Machine Learning`
393 ///
394 /// ```edition2018
395 /// use crossref::{Crossref, WorksQuery, Work};
396 /// # async fn run() -> Result<(), crossref::Error> {
397 /// let client = Crossref::builder().build()?;
398 ///
399 /// let all_works: Vec<Work> = client.deep_page(WorksQuery::new("Machine Learning")).await.into_iter().flat_map(|x|x.items).collect();
400 ///
401 /// # Ok(())
402 /// # }
403 /// ```
404 ///
405 /// # Example
406 ///
407 /// Iterate over all the pages (`WorkList`) of the funder with id `funder id` by using a combined query.
408 /// A single `WorkList` usually holds 20 `Work` items.
409 ///
410 /// ```edition2018
411 /// use crossref::{Crossref, Funders, WorksQuery, Work, WorkList};
412 /// # async fn run() -> Result<(), crossref::Error> {
413 /// let client = Crossref::builder().build()?;
414 ///
415 /// let all_funder_work_list: Vec<WorkList> = client.deep_page(WorksQuery::default().into_combined_query::<Funders>("funder id")).await;
416 ///
417 /// # Ok(())
418 /// # }
419 /// ```
420 /// # Example
421 ///
422 /// Iterate over all `Work` items of a specific funder directly.
423 ///
424 /// ```edition2018
425 /// use crossref::{Crossref, Funders, WorksQuery, Work, WorkList};
426 /// # async fn run() -> Result<(), crossref::Error> {
427 /// let client = Crossref::builder().build()?;
428 ///
429 /// let all_works: Vec<Work> = client.deep_page(WorksQuery::default()
430 /// .into_combined_query::<Funders>("funder id"))
431 /// .await
432 /// .into_iter()
433 /// .flat_map(|x| x.items)
434 /// .collect();
435 ///
436 /// # Ok(())
437 /// # }
438 /// ```
439 ///
440 /// # Example
441 ///
442 /// Alternatively deep page without an iterator by handling the cursor directly
443 ///
444 /// ```edition2018
445 /// use crossref::{Crossref, WorksQuery, WorksFilter};
446 /// # async fn run() -> Result<(), crossref::Error> {
447 /// let client = Crossref::builder().build()?;
448 ///
449 /// // request a next-cursor first
450 /// let query = WorksQuery::new("Machine Learning")
451 /// .new_cursor();
452 ///
453 /// let works = client.works(query.clone()).await?;
454 ///
455 /// // this continues from where this first response stopped
456 /// // if no more work items are available then a empty list will be returned
457 /// let deep_works = client.works(
458 /// query.next_cursor(&works.next_cursor.unwrap())
459 /// ).await?;
460 /// # Ok(())
461 /// # }
462 /// ```
463 ///
464 pub async fn deep_page<T: Into<WorkListQuery>>(&self, query: T) -> Vec<WorkList> {
465 WorkListIterator {
466 query: query.into(),
467 client: self,
468 finish_next_iteration: false,
469 }
470 .process()
471 .await
472 }
473
474 /// Return the `Agency` that registers the `Work` identified by the `doi`.
475 ///
476 /// # Errors
477 /// This method fails if the doi could not identified `ResourceNotFound`
478 ///
479 pub async fn work_agency(&self, doi: &str) -> Result<WorkAgency> {
480 let resp = self.get_response(&Works::Agency(doi.to_string())).await?;
481 get_item!(WorkAgency, resp.message, resp.message_type)
482 }
483
484 /// Return the matching `Funders` items.
485 pub async fn funders(&self, funders: FundersQuery) -> Result<FunderList> {
486 let resp = self.get_response(&Funders::Query(funders)).await?;
487 get_item!(FunderList, resp.message, resp.message_type)
488 }
489
490 /// Return the `Funder` for the `id`
491 pub async fn funder(&self, id: &str) -> Result<Funder> {
492 let resp = self
493 .get_response(&Funders::Identifier(id.to_string()))
494 .await?;
495 get_item!(Funder, resp.message, resp.message_type).map(|x| *x)
496 }
497
498 /// Return the matching `Members` items.
499 pub async fn members(&self, members: MembersQuery) -> Result<MemberList> {
500 let resp = self.get_response(&Members::Query(members)).await?;
501 get_item!(MemberList, resp.message, resp.message_type)
502 }
503
504 /// Return the `Member` for the `id`
505 pub async fn member(&self, member_id: &str) -> Result<Member> {
506 let resp = self
507 .get_response(&Members::Identifier(member_id.to_string()))
508 .await?;
509 get_item!(Member, resp.message, resp.message_type).map(|x| *x)
510 }
511
512 /// Return the `Prefix` for the `id`
513 pub async fn prefix(&self, id: &str) -> Result<Prefix> {
514 let resp = self
515 .get_response(&Prefixes::Identifier(id.to_string()))
516 .await?;
517 get_item!(Prefix, resp.message, resp.message_type)
518 }
519 /// Return a specific `Journal`
520 pub async fn journal(&self, id: &str) -> Result<Journal> {
521 let resp = self
522 .get_response(&Journals::Identifier(id.to_string()))
523 .await?;
524 get_item!(Journal, resp.message, resp.message_type).map(|x| *x)
525 }
526
527 /// Return all available `Type`
528 pub async fn types(&self) -> Result<TypeList> {
529 let resp = self.get_response(&Types::All).await?;
530 get_item!(TypeList, resp.message, resp.message_type)
531 }
532
533 /// Return the `Type` for the `id`
534 pub async fn type_(&self, id: &Type) -> Result<CrossrefType> {
535 let resp = self
536 .get_response(&Types::Identifier(id.id().to_string()))
537 .await?;
538 get_item!(Type, resp.message, resp.message_type)
539 }
540
541 /// Get a random set of DOIs
542 ///
543 /// # Example
544 ///
545 /// ```edition2018
546 /// use crossref::Crossref;
547 /// # async fn run() -> Result<(), crossref::Error> {
548 /// # let client = Crossref::builder().build()?;
549 /// // this will return 10 random dois from the crossref api
550 /// let random_dois = client.random_dois(10).await?;
551 /// # Ok(())
552 /// # }
553 /// ```
554 pub async fn random_dois(&self, len: usize) -> Result<Vec<String>> {
555 self.works(WorksQuery::random(len))
556 .await
557 .map(|x| x.items.into_iter().map(|x| x.doi).collect())
558 }
559}
560
561/// A `CrossrefBuilder` can be used to create `Crossref` with additional config.
562///
563/// # Example
564///
565/// ```edition2018
566/// use crossref::Crossref;
567/// # fn run() -> Result<(), crossref::Error> {
568///
569/// let client = Crossref::builder()
570/// .polite("polite@example.com")
571/// .token("your token")
572/// .build()?;
573/// # Ok(())
574/// # }
575/// ```
576#[derive(Default)]
577pub struct CrossrefBuilder {
578 /// [Good manners = more reliable service.](https://github.com/CrossRef/rest-api-doc#good-manners--more-reliable-service)
579 ///
580 /// will add a `User-Agent` header by default with with the `email` email.
581 /// crossref can contact you if your script misbehaves
582 /// this will get you directed to the "polite pool"
583 user_agent: Option<String>,
584 /// the token for the Crossref Plus service will be included as `Authorization` header
585 /// This token will ensure that said requests get directed to a pool of machines that are reserved for "Plus" SLA users.
586 plus_token: Option<String>,
587 /// use a different base url than `Crossref::BASE_URL` https://api.crossref.org
588 base_url: Option<String>,
589 /// optional caller-supplied `reqwest::Client` that overrides the one built from headers
590 http_client: Option<Client>,
591}
592
593impl CrossrefBuilder {
594 /// Constructs a new `CrossrefBuilder`.
595 ///
596 /// This is the same as `Crossref::builder()`.
597 pub fn new() -> CrossrefBuilder {
598 CrossrefBuilder::default()
599 }
600
601 /// be polite and set your email as `User-Agent`
602 /// will get you in the polite pool of crossref
603 pub fn polite(mut self, email: &str) -> Self {
604 self.user_agent = Some(format!("mailto:{}", email));
605 self
606 }
607
608 /// set the user agent directly
609 pub fn user_agent(mut self, user_agent: &str) -> Self {
610 self.user_agent = Some(user_agent.to_string());
611 self
612 }
613
614 /// set a crossref plus service API token
615 pub fn token(mut self, token: &str) -> Self {
616 self.plus_token = Some(token.to_string());
617 self
618 }
619
620 /// Overrides the API base URL. Lets tests redirect every request
621 /// to a wiremock server: `.base_url(mock.uri())`.
622 pub fn base_url(mut self, url: impl Into<String>) -> Self {
623 self.base_url = Some(url.into());
624 self
625 }
626
627 /// Replaces the internal `reqwest::Client`. Useful for sharing a
628 /// connection pool, embedding middleware (retry layers, tracing,
629 /// custom user-agent), or in tests that want fast-fail timeouts.
630 /// When set, the `polite`, `user_agent`, and `token` headers are
631 /// not applied — the caller is responsible for any headers they
632 /// want on the provided client.
633 pub fn http_client(mut self, client: reqwest::Client) -> Self {
634 self.http_client = Some(client);
635 self
636 }
637
638 /// Returns a `Crossref` that uses this `CrossrefBuilder` configuration.
639 /// # Errors
640 ///
641 /// This will fail if TLS backend cannot be initialized see [reqwest::ClientBuilder::build]
642 pub fn build(self) -> Result<Crossref> {
643 let http_client = match self.http_client {
644 Some(client) => client,
645 None => {
646 use reqwest::header;
647 let mut headers = header::HeaderMap::new();
648 if let Some(agent) = &self.user_agent {
649 headers.insert(
650 header::USER_AGENT,
651 header::HeaderValue::from_str(agent).map_err(|_| Error::Config {
652 msg: format!("failed to create User Agent header for `{}`", agent),
653 })?,
654 );
655 }
656 if let Some(token) = &self.plus_token {
657 headers.insert(
658 header::AUTHORIZATION,
659 header::HeaderValue::from_str(token).map_err(|_| Error::Config {
660 msg: format!("failed to create AUTHORIZATION header for `{}`", token),
661 })?,
662 );
663 }
664 reqwest::Client::builder()
665 .default_headers(headers)
666 .build()
667 .map_err(|_| Error::Config {
668 msg: "failed to initialize TLS backend".to_string(),
669 })?
670 }
671 };
672
673 Ok(Crossref {
674 base_url: self
675 .base_url
676 .unwrap_or_else(|| Crossref::BASE_URL.to_string()),
677 http_client,
678 })
679 }
680}
681
682/// Allows iterating of deep page work request
683pub struct WorkListIterator<'a> {
684 /// the query
685 query: WorkListQuery,
686 /// performs each request
687 client: &'a Crossref,
688 /// whether the iterator should finish next iteration
689 finish_next_iteration: bool,
690}
691impl<'a> WorkListIterator<'a> {
692 /// Process all remaining items and collect them into a `Vec<WorkList>`
693 pub async fn process(&mut self) -> Vec<WorkList> {
694 let mut ret = vec![];
695 while let Some(x) = self.next().await {
696 ret.push(x);
697 }
698 ret
699 }
700
701 async fn next(&mut self) -> Option<WorkList> {
702 if self.finish_next_iteration {
703 return None;
704 }
705
706 {
707 let control = &mut self.query.query_mut().result_control;
708
709 // if no result control is set, set a new cursor
710 if control.is_none() {
711 *control = Some(WorkResultControl::new_cursor());
712 }
713 }
714
715 let resp = self.client.get_response(&self.query).await;
716 if let Ok(resp) = resp {
717 let worklist: Result<WorkList> = get_item!(WorkList, resp.message, resp.message_type);
718 if let Ok(worklist) = worklist {
719 if let Some(cursor) = &worklist.next_cursor {
720 match &mut self.query.query_mut().result_control {
721 Some(WorkResultControl::Cursor { token, .. }) => {
722 // use the received cursor token in next iteration
723 *token = Some(cursor.clone())
724 }
725 Some(WorkResultControl::Standard(_)) => {
726 // standard result control was set, don't deep page and return next iteration
727 self.finish_next_iteration = true;
728 }
729 _ => (),
730 }
731 } else {
732 // no cursor received, end next iteration
733 self.finish_next_iteration = true;
734 }
735
736 if worklist.items.is_empty() {
737 None
738 } else {
739 Some(worklist)
740 }
741 } else {
742 // failed to deserialize response into `WorkList`
743 None
744 }
745 } else {
746 // no response received
747 None
748 }
749 }
750}