Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: add example & more to req.query() #479

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,50 @@ impl<State> Request<State> {
Ok(serde_json::from_slice(&body_bytes).map_err(|_| std::io::ErrorKind::InvalidData)?)
}

/// Get the URL querystring.
/// Extract and parse a query string parameter by name.
///
/// Returns the results of parsing the parameter according to the inferred
/// output type `T`, which must have the `serde::Deserialize` trait and be
/// able to have the `'de` lifetime.
///
/// The name should *not* include any of the key-value formatting
/// characters (`?`, `=`, or `&`).
///
/// If no query string exists on the uri, this method will default to
/// parsing an empty string so that deserialization can be succesful to
/// structs where all fields are optional.
///
/// # Errors
///
/// Yields an `Err` if the parameters were found but failed to parse into an
/// instance of type `T`.
///
/// # Panics
///
/// Panic if `key` is not a parameter within the query string.
///
/// # Examples
///
/// ```no_run
/// # use futures::executor::block_on;
/// # fn main() -> Result<(), std::io::Error> { block_on(async {
/// #
/// use tide::Request;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct QueryParams {
/// _param_name: String,
/// }
///
/// let mut app = tide::new();
/// app.at("/").get(|req: Request<()>| async move {
/// let _query_params: QueryParams = req.query::<QueryParams>().unwrap();
/// Ok("")
/// });
/// #
/// # Ok(()) })}
/// ```
pub fn query<'de, T: Deserialize<'de>>(&'de self) -> Result<T, crate::Error> {
// Default to an empty query string if no query parameter has been specified.
// This allows successful deserialisation of structs where all fields are optional
Expand Down