Line data Source code
1 : use core::fmt;
2 : use std::{borrow::Cow, str::FromStr};
3 :
4 : use super::error::ApiError;
5 : use anyhow::anyhow;
6 : use hyper::{body::HttpBody, Body, Request};
7 : use routerify::ext::RequestExt;
8 :
9 18779 : pub fn get_request_param<'a>(
10 18779 : request: &'a Request<Body>,
11 18779 : param_name: &str,
12 18779 : ) -> Result<&'a str, ApiError> {
13 18779 : match request.param(param_name) {
14 18779 : Some(arg) => Ok(arg),
15 0 : None => Err(ApiError::BadRequest(anyhow!(
16 0 : "no {param_name} specified in path param",
17 0 : ))),
18 : }
19 18779 : }
20 :
21 16571 : pub fn parse_request_param<T: FromStr>(
22 16571 : request: &Request<Body>,
23 16571 : param_name: &str,
24 16571 : ) -> Result<T, ApiError> {
25 16571 : match get_request_param(request, param_name)?.parse() {
26 16571 : Ok(v) => Ok(v),
27 0 : Err(_) => Err(ApiError::BadRequest(anyhow!(
28 0 : "failed to parse {param_name}",
29 0 : ))),
30 : }
31 16571 : }
32 :
33 6556 : fn get_query_param<'a>(
34 6556 : request: &'a Request<Body>,
35 6556 : param_name: &str,
36 6556 : ) -> Result<Option<Cow<'a, str>>, ApiError> {
37 6556 : let query = match request.uri().query() {
38 308 : Some(q) => q,
39 6248 : None => return Ok(None),
40 : };
41 308 : let mut values = url::form_urlencoded::parse(query.as_bytes())
42 458 : .filter_map(|(k, v)| if k == param_name { Some(v) } else { None })
43 308 : // we call .next() twice below. If it's None the first time, .fuse() ensures it's None afterwards
44 308 : .fuse();
45 308 :
46 308 : let value1 = values.next();
47 308 : if values.next().is_some() {
48 0 : return Err(ApiError::BadRequest(anyhow!(
49 0 : "param {param_name} specified more than once"
50 0 : )));
51 308 : }
52 308 : Ok(value1)
53 6556 : }
54 :
55 27 : pub fn must_get_query_param<'a>(
56 27 : request: &'a Request<Body>,
57 27 : param_name: &str,
58 27 : ) -> Result<Cow<'a, str>, ApiError> {
59 27 : get_query_param(request, param_name)?.ok_or_else(|| {
60 0 : ApiError::BadRequest(anyhow!("no {param_name} specified in query parameters"))
61 27 : })
62 27 : }
63 :
64 6529 : pub fn parse_query_param<E: fmt::Display, T: FromStr<Err = E>>(
65 6529 : request: &Request<Body>,
66 6529 : param_name: &str,
67 6529 : ) -> Result<Option<T>, ApiError> {
68 6529 : get_query_param(request, param_name)?
69 6529 : .map(|v| {
70 223 : v.parse().map_err(|e| {
71 0 : ApiError::BadRequest(anyhow!("cannot parse query param {param_name}: {e}"))
72 223 : })
73 6529 : })
74 6529 : .transpose()
75 6529 : }
76 :
77 24 : pub async fn ensure_no_body(request: &mut Request<Body>) -> Result<(), ApiError> {
78 24 : match request.body_mut().data().await {
79 0 : Some(_) => Err(ApiError::BadRequest(anyhow!("Unexpected request body"))),
80 24 : None => Ok(()),
81 : }
82 24 : }
|