Added MultipartFile extractors.

Moved cfg macro to lib where possible.

Changed some features, and made some deps optional
This commit is contained in:
Martin Berg Alstad
2024-06-30 20:16:17 +02:00
parent e0baff8625
commit 0898a50166
17 changed files with 287 additions and 55 deletions

View File

@ -1,4 +1,3 @@
#[cfg(feature = "axum")]
use {
axum::{extract::Request, handler::Handler, Router, ServiceExt},
std::net::Ipv4Addr,
@ -11,12 +10,11 @@ use {
},
tracing::{info, Level},
};
#[cfg(all(feature = "axum", feature = "tokio"))]
#[cfg(feature = "tokio")]
use {std::io, std::net::SocketAddr, tokio::net::TcpListener};
// TODO trim trailing slash into macro > let _app = NormalizePathLayer::trim_trailing_slash().layer(create_app!(routes));
#[macro_export]
#[cfg(feature = "axum")]
macro_rules! create_app {
($router:expr) => {
$router
@ -27,7 +25,6 @@ macro_rules! create_app {
}
#[derive(Default)]
#[cfg(feature = "axum")]
pub struct AppBuilder {
router: Router,
socket: Option<(Ipv4Addr, u16)>,
@ -36,7 +33,6 @@ pub struct AppBuilder {
tracing: Option<TraceLayer<HttpMakeClassifier>>,
}
#[cfg(all(feature = "axum", feature = "tokio"))]
impl AppBuilder {
pub fn new() -> Self {
Self::default()
@ -81,8 +77,9 @@ impl AppBuilder {
self
}
#[cfg(feature = "tokio")]
pub async fn serve(self) -> io::Result<()> {
let _ = fmt_trace();
let _ = fmt_trace(); // Allowed to fail
let listener = self.listener().await?;
if self.normalize_path.unwrap_or(true) {
@ -95,6 +92,7 @@ impl AppBuilder {
Ok(())
}
#[cfg(feature = "tokio")]
async fn listener(&self) -> io::Result<TcpListener> {
let addr = SocketAddr::from(self.socket.unwrap_or((Ipv4Addr::UNSPECIFIED, 8000)));
info!("Initializing server on: {addr}");
@ -124,7 +122,7 @@ fn fmt_trace() -> Result<(), String> {
.map_err(|error| error.to_string())
}
#[cfg(all(test, feature = "axum"))]
#[cfg(test)]
mod tests {
use axum::Router;

187
src/axum/extractor.rs Normal file
View File

@ -0,0 +1,187 @@
use axum::{
async_trait,
extract::{
multipart::{Field, MultipartError, MultipartRejection},
FromRequest, Multipart, Request,
},
response::IntoResponse,
};
use thiserror::Error;
#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
pub enum ContentType {
Json,
Form,
Multipart,
Pdf,
Html,
Unknown,
}
impl From<&str> for ContentType {
fn from(content_type: &str) -> Self {
match content_type {
"application/json" => ContentType::Json,
"application/x-www-form-urlencoded" => ContentType::Form,
"multipart/form-data" => ContentType::Multipart,
"application/pdf" => ContentType::Pdf,
"text/html" => ContentType::Html,
_ => ContentType::Unknown,
}
}
}
impl From<String> for ContentType {
fn from(content_type: String) -> Self {
ContentType::from(content_type.as_str())
}
}
impl From<Option<&str>> for ContentType {
fn from(content_type: Option<&str>) -> Self {
content_type
.map(ContentType::from)
.unwrap_or(ContentType::Unknown)
}
}
pub struct File {
pub filename: String,
pub bytes: Vec<u8>,
pub content_type: ContentType,
}
impl File {
pub fn new(
filename: impl Into<String>,
bytes: impl Into<Vec<u8>>,
content_type: impl Into<ContentType>,
) -> Self {
Self {
filename: filename.into(),
bytes: bytes.into(),
content_type: content_type.into(),
}
}
async fn from_field(field: Field<'_>) -> Result<Self, MultipartFileRejection> {
let filename = field
.file_name()
.ok_or(MultipartFileRejection::MissingFilename)?
.to_string();
let content_type: ContentType = field.content_type().into();
let bytes = field.bytes().await?;
Ok(File::new(filename, bytes, content_type))
}
}
/// Extractor for a single file from a multipart request.
/// Expects exactly one file. A file must have a name, bytes and optionally a content type.
/// This extractor consumes the request and must ble placed last in the handler.
pub struct MultipartFile(pub File);
/// Extractor for multiple files from a multipart request.
/// Expects at least one file. A file must have a name, bytes and optionally a content type.
/// This extractor consumes the request and must ble placed last in the handler.
pub struct MultipartFiles(pub Vec<File>);
#[derive(Debug, Error)]
pub enum MultipartFileRejection {
#[error(transparent)]
MultipartRejection(#[from] MultipartRejection),
#[error("Field error: {0}")]
FieldError(String),
#[error("No files found")]
NoFiles,
#[error("Expected one file, got several")]
SeveralFiles,
#[error("Missing filename")]
MissingFilename,
#[error("Error in body of multipart: {0}")]
BodyError(String),
}
impl From<MultipartError> for MultipartFileRejection {
fn from(error: MultipartError) -> Self {
MultipartFileRejection::BodyError(error.body_text())
}
}
impl IntoResponse for MultipartFileRejection {
fn into_response(self) -> axum::response::Response {
match self {
MultipartFileRejection::MultipartRejection(rejection) => rejection.into_response(),
MultipartFileRejection::FieldError(error) => {
(axum::http::StatusCode::BAD_REQUEST, error).into_response()
}
MultipartFileRejection::NoFiles => {
(axum::http::StatusCode::BAD_REQUEST, "No files found").into_response()
}
MultipartFileRejection::SeveralFiles => (
axum::http::StatusCode::BAD_REQUEST,
"Expected one file, got several",
)
.into_response(),
MultipartFileRejection::MissingFilename => {
(axum::http::StatusCode::BAD_REQUEST, "Missing filename").into_response()
}
MultipartFileRejection::BodyError(error) => {
(axum::http::StatusCode::BAD_REQUEST, error).into_response()
}
}
}
}
#[async_trait]
impl<S> FromRequest<S> for MultipartFile
where
S: Send + Sync,
{
type Rejection = MultipartFileRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let mut multipart = Multipart::from_request(req, state).await?;
let fields = get_fields(&mut multipart).await?;
if fields.len() > 1 {
Err(MultipartFileRejection::SeveralFiles)
} else {
let field = fields
.into_iter()
.next()
.ok_or(MultipartFileRejection::NoFiles)?;
Ok(MultipartFile(File::from_field(field).await?))
}
}
}
#[async_trait]
impl<S> FromRequest<S> for MultipartFiles
where
S: Send + Sync,
{
type Rejection = MultipartFileRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
let mut multipart = Multipart::from_request(req, state).await?;
let fields = get_fields(&mut multipart).await?;
if fields.is_empty() {
Err(MultipartFileRejection::NoFiles)
} else {
let mut files = vec![];
for field in fields.into_iter() {
files.push(File::from_field(field).await?);
}
Ok(MultipartFiles(files))
}
}
}
async fn get_fields<'a>(
multipart: &'a mut Multipart,
) -> Result<Vec<Field<'a>>, MultipartFileRejection> {
let fields: Vec<Field> = multipart.next_field().await?.into_iter().collect();
if fields.is_empty() {
Err(MultipartFileRejection::NoFiles)
} else {
Ok(fields)
}
}

View File

@ -1,4 +1,4 @@
#[cfg(all(feature = "tokio", feature = "axum"))]
#[cfg(feature = "tokio")]
use {crate::io::file, axum::body::Body, axum::response::Html, std::io};
/// Load an HTML file from the given file path, relative to the current directory.
@ -10,7 +10,7 @@ use {crate::io::file, axum::body::Body, axum::response::Html, std::io};
/// ```
/// let html = async { lib::axum::load::load_html("openapi.html").await.unwrap() };
/// ```
#[cfg(all(feature = "tokio", feature = "axum"))]
#[cfg(feature = "tokio")]
pub async fn load_html<Path>(file_path: Path) -> Result<Html<Body>, io::Error>
where
Path: AsRef<std::path::Path>,
@ -18,7 +18,7 @@ where
load_file(file_path).await.map(Html)
}
#[cfg(all(feature = "tokio", feature = "axum"))]
#[cfg(feature = "tokio")]
pub async fn load_file<Path>(file_path: Path) -> Result<Body, io::Error>
where
Path: AsRef<std::path::Path>,
@ -38,7 +38,6 @@ where
/// ```
// TODO check platform and use correct path separator
#[macro_export]
#[cfg(feature = "axum")]
macro_rules! load_html {
($filepath:expr) => {
axum::response::Html(
@ -58,7 +57,7 @@ macro_rules! load_html {
};
}
#[cfg(all(test, feature = "axum"))]
#[cfg(test)]
mod tests {
#[test]
fn test_load_html() {

View File

@ -1,4 +1,6 @@
pub mod app;
pub mod extractor;
pub mod load;
#[cfg(feature = "serde")]
pub mod response;
pub mod router;

View File

@ -1,4 +1,3 @@
#[cfg(all(feature = "axum", feature = "serde"))]
use {
crate::serde::response::BaseResponse,
axum::{
@ -8,14 +7,13 @@ use {
serde::Serialize,
};
#[cfg(all(feature = "axum", feature = "serde"))]
impl<T: Serialize> IntoResponse for BaseResponse<T> {
fn into_response(self) -> Response {
Json(self).into_response()
}
}
#[cfg(all(test, feature = "axum", feature = "serde"))]
#[cfg(test)]
mod tests {
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderValue, StatusCode};

View File

@ -18,7 +18,6 @@
/// ));
/// ```
#[macro_export]
#[cfg(feature = "axum")]
macro_rules! router {
($body:expr) => {
pub(crate) fn router() -> axum::Router {
@ -52,7 +51,6 @@ macro_rules! router {
/// );
/// ```
#[macro_export]
#[cfg(feature = "axum")]
macro_rules! routes {
($($method:ident $route:expr => $func:expr),* $(,)?) => {
axum::Router::new()
@ -63,7 +61,6 @@ macro_rules! routes {
}
#[macro_export]
#[cfg(feature = "axum")]
macro_rules! join_routes {
($($route:expr),* $(,)?) => {
axum::Router::new()$(
@ -72,7 +69,7 @@ macro_rules! join_routes {
};
}
#[cfg(all(test, feature = "axum"))]
#[cfg(test)]
mod tests {
use axum::extract::State;
use axum::Router;
@ -117,7 +114,7 @@ mod tests {
#[test]
fn test_routes() {
let _router: Router<()> = routes!(
let _router: Router = routes!(
get "/" => index,
post "/" => || async {}
);