Files
google-apis-rs/gen/chromeuxreport1/src/lib.rs
2020-07-10 09:41:44 +08:00

851 lines
34 KiB
Rust

// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Chrome UX Report* crate version *1.0.14+20200708*, where *20200708* is the exact revision of the *chromeuxreport:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.14*.
//!
//! Everything else about the *Chrome UX Report* *v1* API can be found at the
//! [official documentation site](https://developers.google.com/web/tools/chrome-user-experience-report/api/reference).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/chromeuxreport1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.ChromeUXReport.html) ...
//!
//! * [records](struct.Record.html)
//! * [*query record*](struct.RecordQueryRecordCall.html)
//!
//!
//!
//!
//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](struct.ChromeUXReport.html)**
//! * a central object to maintain state and allow accessing all *Activities*
//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn
//! allow access to individual [*Call Builders*](trait.CallBuilder.html)
//! * **[Resources](trait.Resource.html)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*
//! * **[Parts](trait.Part.html)**
//! * a collection of properties
//! * never directly used in *Activities*
//! * **[Activities](trait.CallBuilder.html)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity(...).doit()
//! ```
//!
//! Or specifically ...
//!
//! ```ignore
//! let r = hub.records().query_record(...).doit()
//! ```
//!
//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
//! The `doit()` method performs the actual communication with the server and returns the respective result.
//!
//! # Usage
//!
//! ## Setting up your Project
//!
//! To use this library, you would put the following lines into your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! google-chromeuxreport1 = "*"
//! # This project intentionally uses an old version of Hyper. See
//! # https://github.com/Byron/google-apis-rs/issues/173 for more
//! # information.
//! hyper = "^0.10"
//! hyper-rustls = "^0.6"
//! serde = "^1.0"
//! serde_json = "^1.0"
//! yup-oauth2 = "^1.0"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate hyper_rustls;
//! extern crate yup_oauth2 as oauth2;
//! extern crate google_chromeuxreport1 as chromeuxreport1;
//! use chromeuxreport1::QueryRequest;
//! use chromeuxreport1::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use chromeuxreport1::ChromeUXReport;
//!
//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and
//! // `client_secret`, among other things.
//! let secret: ApplicationSecret = Default::default();
//! // Instantiate the authenticator. It will choose a suitable authentication flow for you,
//! // unless you replace `None` with the desired Flow.
//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
//! <MemoryStorage as Default>::default(), None);
//! let mut hub = ChromeUXReport::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
//! // As the method needs a request, you would usually fill it with the desired information
//! // into the respective structure. Some of the parts shown here might not be applicable !
//! // Values shown here are possibly random and not representative !
//! let mut req = QueryRequest::default();
//!
//! // You can configure optional parameters by calling the respective setters at will, and
//! // execute the final call using `doit()`.
//! // Values shown here are possibly random and not representative !
//! let result = hub.records().query_record(req)
//! .doit();
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## Handling Errors
//!
//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of
//! the doit() methods, or handed as possibly intermediate results to either the
//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
//!
//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
//! makes the system potentially resilient to all kinds of errors.
//!
//! ## Uploads and Downloads
//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be
//! read by you to obtain the media.
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default.
//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
//! this call: `.param("alt", "media")`.
//!
//! Methods supporting uploads can do so using up to 2 different protocols:
//! *simple* and *resumable*. The distinctiveness of each is represented by customized
//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
//!
//! ## Customization and Callbacks
//!
//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the
//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call.
//! Respective methods will be called to provide progress information, as well as determine whether the system should
//! retry on failure.
//!
//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [encodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](trait.Part.html) which are identifiable by name, which will be sent to
//! the server to indicate either the set parts of the request or the desired parts in the response.
//!
//! ## Builder Arguments
//!
//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
//! These will always take a single argument, for which the following statements are true.
//!
//! * [PODs][wiki-pod] are handed by copy
//! * strings are passed as `&str`
//! * [request values](trait.RequestValue.html) are moved
//!
//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
//!
//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
//! [google-go-api]: https://github.com/google/google-api-go-client
//!
//!
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut, dead_code)]
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
#[macro_use]
extern crate serde_derive;
extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use std::time::Duration;
pub use cmn::*;
// ##############
// UTILITIES ###
// ############
// ########
// HUB ###
// ######
/// Central instance to access all ChromeUXReport related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_chromeuxreport1 as chromeuxreport1;
/// use chromeuxreport1::QueryRequest;
/// use chromeuxreport1::{Result, Error};
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use chromeuxreport1::ChromeUXReport;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = ChromeUXReport::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = QueryRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.records().query_record(req)
/// .doit();
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct ChromeUXReport<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C, A> Hub for ChromeUXReport<C, A> {}
impl<'a, C, A> ChromeUXReport<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> ChromeUXReport<C, A> {
ChromeUXReport {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/1.0.14".to_string(),
_base_url: "https://chromeuxreport.googleapis.com/".to_string(),
_root_url: "https://chromeuxreport.googleapis.com/".to_string(),
}
}
pub fn records(&'a self) -> RecordMethods<'a, C, A> {
RecordMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/1.0.14`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://chromeuxreport.googleapis.com/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://chromeuxreport.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// A bin is a discrete portion of data spanning from start to end, or if no
/// end is given, then from start to +inf.
///
/// A bin's start and end values are given in the value type of the metric it
/// represents. For example, "first contentful paint" is measured in
/// milliseconds and exposed as ints, therefore its metric bins will use int32s
/// for its start and end types. However, "cumulative layout shift" is measured
/// in unitless decimals and is exposed as a decimal encoded as a string,
/// therefore its metric bins will use strings for its value type.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Bin {
/// Start is the beginning of the data bin.
pub start: Option<String>,
/// End is the end of the data bin. If end is not populated, then the bin has
/// no end and is valid from start to +inf.
pub end: Option<String>,
/// The proportion of users that experienced this bin's value for the given
/// metric.
pub density: Option<f64>,
}
impl Part for Bin {}
/// Request payload sent by a physical web client.
///
/// This request includes all necessary context to load a particular
/// user experience record.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [query record records](struct.RecordQueryRecordCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct QueryRequest {
/// The metrics that should be included in the response.
/// If none are specified then any metrics found will be returned.
///
/// Allowed values: ["first_contentful_paint",
/// "first_input_delay", "largest_contentful_paint",
/// "cumulative_layout_shift"]
pub metrics: Option<Vec<String>>,
/// The form factor is a query dimension that specifies the device class that
/// the record's data should belong to.
///
/// Note: If no form factor is specified, then a special record with
/// aggregated data over all form factors will be returned.
#[serde(rename="formFactor")]
pub form_factor: Option<String>,
/// The url pattern "url" refers to a url pattern that is any arbitrary url.
///
/// Examples: "https://example.com/",
/// "https://cloud.google.com/why-google-cloud/"
pub url: Option<String>,
/// The url pattern "origin" refers to a url pattern that is the origin of
/// a website.
///
/// Examples: "https://example.com", "https://cloud.google.com"
pub origin: Option<String>,
}
impl RequestValue for QueryRequest {}
/// A `metric` is a set of user experience data for a single web performance
/// metric, like "first contentful paint". It contains a summary histogram of
/// real world Chrome usage as a series of `bins`.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Metric {
/// Common useful percentiles of the Metric. The value type for the
/// percentiles will be the same as the value types given for the Histogram
/// bins.
pub percentiles: Option<Percentiles>,
/// The histogram of user experiences for a metric. The histogram will have at
/// least one bin and the densities of all bins will add up to ~1.
pub histogram: Option<Vec<Bin>>,
}
impl Part for Metric {}
/// Record is a single Chrome UX report data record. It contains use experience
/// statistics for a single url pattern and set of dimensions.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [query record records](struct.RecordQueryRecordCall.html) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Record {
/// Metrics is the map of user experience data available for the record defined
/// in the key field. Metrics are keyed on the metric name.
///
/// Allowed key values: ["first_contentful_paint",
/// "first_input_delay", "largest_contentful_paint",
/// "cumulative_layout_shift"]
pub metrics: Option<HashMap<String, Metric>>,
/// Key defines all of the unique querying parameters needed to look up a user
/// experience record.
pub key: Option<Key>,
}
impl Resource for Record {}
/// Object representing the normalization actions taken to normalize a url to
/// achieve a higher chance of successful lookup. These are simple automated
/// changes that are taken when looking up the provided `url_patten` would be
/// known to fail. Complex actions like following redirects are not handled.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct UrlNormalization {
/// The original requested URL prior to any normalization actions.
#[serde(rename="originalUrl")]
pub original_url: Option<String>,
/// The URL after any normalization actions. This is a valid user experience
/// URL that could reasonably be looked up.
#[serde(rename="normalizedUrl")]
pub normalized_url: Option<String>,
}
impl Part for UrlNormalization {}
/// Percentiles contains synthetic values of a metric at a given statistical
/// percentile. These are used for estimating a metric's value as experienced
/// by a percentage of users out of the total number of users.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Percentiles {
/// 75% of users experienced the given metric at or below this value.
pub p75: Option<String>,
}
impl Part for Percentiles {}
/// Key defines all the dimensions that identify this record as unique.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Key {
/// Origin specifies the origin that this record is for.
///
/// Note: When specifying an origin, data for loads under this origin over
/// all pages are aggregated into origin level user experience data.
pub origin: Option<String>,
/// The form factor is the device class that all users used to access the
/// site for this record.
///
/// If the form factor is unspecified, then aggregated data over all form
/// factors will be returned.
#[serde(rename="formFactor")]
pub form_factor: Option<String>,
/// Url specifies a specific url that this record is for.
///
/// Note: When specifying a "url" only data for that specific url will be
/// aggregated.
pub url: Option<String>,
}
impl Part for Key {}
/// Response payload sent back to a physical web client.
///
/// This response contains the record found based on the identiers present in a
/// `QueryRequest`. The returned response will have a record, and sometimes
/// details on normalization actions taken on the request that were necessary to
/// make the request successful.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [query record records](struct.RecordQueryRecordCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct QueryResponse {
/// The record that was found.
pub record: Option<Record>,
/// These are details about automated normalization actions that were taken in
/// order to make the requested `url_pattern` valid.
#[serde(rename="urlNormalizationDetails")]
pub url_normalization_details: Option<UrlNormalization>,
}
impl ResponseResult for QueryResponse {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *record* resources.
/// It is not used directly, but through the `ChromeUXReport` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_chromeuxreport1 as chromeuxreport1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use chromeuxreport1::ChromeUXReport;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = ChromeUXReport::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `query_record(...)`
/// // to build up your call.
/// let rb = hub.records();
/// # }
/// ```
pub struct RecordMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a ChromeUXReport<C, A>,
}
impl<'a, C, A> MethodsBuilder for RecordMethods<'a, C, A> {}
impl<'a, C, A> RecordMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Queries the Chrome User Experience for a single `record` for a given site.
///
/// Returns a `record` that contains one or more `metrics` corresponding to
/// performance data about the requested site.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn query_record(&self, request: QueryRequest) -> RecordQueryRecordCall<'a, C, A> {
RecordQueryRecordCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Queries the Chrome User Experience for a single `record` for a given site.
///
/// Returns a `record` that contains one or more `metrics` corresponding to
/// performance data about the requested site.
///
/// A builder for the *queryRecord* method supported by a *record* resource.
/// It is not used directly, but through a `RecordMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_chromeuxreport1 as chromeuxreport1;
/// use chromeuxreport1::QueryRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use chromeuxreport1::ChromeUXReport;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = ChromeUXReport::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = QueryRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.records().query_record(req)
/// .doit();
/// # }
/// ```
pub struct RecordQueryRecordCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a ChromeUXReport<C, A>,
_request: QueryRequest,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
}
impl<'a, C, A> CallBuilder for RecordQueryRecordCall<'a, C, A> {}
impl<'a, C, A> RecordQueryRecordCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, QueryResponse)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "chromeuxreport.records.queryRecord",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/records:queryRecord";
let mut key = self.hub.auth.borrow_mut().api_key();
if key.is_none() {
key = dlg.api_key();
}
match key {
Some(value) => params.push(("key", value)),
None => {
dlg.finished(false);
return Err(Error::MissingAPIKey)
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: QueryRequest) -> RecordQueryRecordCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> RecordQueryRecordCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *access_token* (query-string) - OAuth access token.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *callback* (query-string) - JSONP
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *alt* (query-string) - Data format for response.
/// * *$.xgafv* (query-string) - V1 error format.
pub fn param<T>(mut self, name: T, value: T) -> RecordQueryRecordCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
}