fraiseql_server/middleware/
content_type.rs1use axum::{
8 body::Body,
9 http::{Method, Request, StatusCode, header::CONTENT_TYPE},
10 middleware::Next,
11 response::{IntoResponse, Response},
12};
13
14pub async fn require_json_content_type(
25 req: Request<Body>,
26 next: Next,
27) -> Result<Response, Response> {
28 if req.method() != Method::POST {
29 return Ok(next.run(req).await);
30 }
31
32 let content_type = req.headers().get(CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("");
33
34 if !content_type.starts_with("application/json") {
35 let body = serde_json::json!({
36 "errors": [{
37 "message": "Content-Type must be application/json",
38 "extensions": { "code": "UNSUPPORTED_MEDIA_TYPE" }
39 }]
40 });
41 return Err((
42 StatusCode::UNSUPPORTED_MEDIA_TYPE,
43 [(CONTENT_TYPE, "application/json")],
44 serde_json::to_string(&body).unwrap_or_else(|_| {
45 r#"{"errors":[{"message":"Unsupported Media Type"}]}"#.to_owned()
46 }),
47 )
48 .into_response());
49 }
50
51 Ok(next.run(req).await)
52}