use crate::accept_query::{format_accept_query, matches_media_range};
use crate::consts::{HEADER_CONTENT_TYPE, METHOD_QUERY};
use http::HeaderMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryRejection {
NotQuery,
MissingContentType,
UnsupportedMediaType,
}
impl QueryRejection {
pub fn status(self) -> u16 {
match self {
QueryRejection::NotQuery => 405,
QueryRejection::MissingContentType => 400,
QueryRejection::UnsupportedMediaType => 415,
}
}
}
pub fn check_query_request(
method: &str,
headers: &HeaderMap,
accept_query: &[&str],
) -> Result<(), QueryRejection> {
if !method.eq_ignore_ascii_case(METHOD_QUERY) {
return Err(QueryRejection::NotQuery);
}
let content_type = headers
.get(HEADER_CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty());
let content_type = match content_type {
Some(value) => value,
None => return Err(QueryRejection::MissingContentType),
};
if !accept_query.is_empty() {
let media_type = content_type.split(';').next().unwrap_or("").trim();
let accepted = accept_query
.iter()
.any(|range| matches_media_range(range, media_type));
if !accepted {
return Err(QueryRejection::UnsupportedMediaType);
}
}
Ok(())
}
pub fn accept_query_header(media_types: &[&str]) -> String {
format_accept_query(media_types.iter().copied())
}
#[cfg(test)]
mod tests {
use super::*;
use http::HeaderValue;
fn ct(value: &str) -> HeaderMap {
let mut h = HeaderMap::new();
if !value.is_empty() {
h.insert(HEADER_CONTENT_TYPE, HeaderValue::from_str(value).unwrap());
}
h
}
#[test]
fn rejects_non_query() {
let err = check_query_request("GET", &ct("application/json"), &[]).unwrap_err();
assert_eq!(err, QueryRejection::NotQuery);
assert_eq!(err.status(), 405);
}
#[test]
fn rejects_missing_content_type() {
let err = check_query_request("QUERY", &ct(""), &[]).unwrap_err();
assert_eq!(err, QueryRejection::MissingContentType);
assert_eq!(err.status(), 400);
}
#[test]
fn rejects_unsupported_media_type() {
let err =
check_query_request("QUERY", &ct("text/plain"), &["application/json"]).unwrap_err();
assert_eq!(err, QueryRejection::UnsupportedMediaType);
assert_eq!(err.status(), 415);
}
#[test]
fn accepts_supported_query() {
assert!(check_query_request(
"query",
&ct("application/json; charset=utf-8"),
&["application/json"]
)
.is_ok());
}
#[test]
fn builds_accept_query_header() {
assert_eq!(
accept_query_header(&["application/json", "3d/model"]),
r#"application/json, "3d/model""#
);
}
}