HomeDisk/server/src/middleware/validate_json.rs

21 lines
913 B
Rust
Raw Normal View History

use axum::{extract::rejection::JsonRejection, Json};
use homedisk_types::errors::ServerError;
2022-06-08 17:08:06 +00:00
/// Validate json request
2022-07-26 14:46:19 +00:00
pub fn validate_json<T>(payload: Result<Json<T>, JsonRejection>) -> Result<Json<T>, ServerError> {
match payload {
2022-06-11 08:19:47 +00:00
// if success return payload
Ok(payload) => Ok(payload),
2022-06-11 08:19:47 +00:00
// mission json in Content-Type Header
Err(JsonRejection::MissingJsonContentType(_)) => Err(ServerError::InvalidContentType),
2022-06-11 08:19:47 +00:00
// failed to deserialize json
Err(JsonRejection::JsonDataError(_)) => Err(ServerError::JsonDataError),
2022-06-11 08:19:47 +00:00
// syntax error in json
Err(JsonRejection::JsonSyntaxError(_)) => Err(ServerError::JsonSyntaxError),
2022-06-11 08:19:47 +00:00
// failed to extract the request body
Err(JsonRejection::BytesRejection(_)) => Err(ServerError::BytesRejection),
2022-06-11 08:19:47 +00:00
// other error
Err(err) => Err(ServerError::Other(err.to_string())),
}
}