handle stuff using rejection

This commit is contained in:
blek 2023-10-01 12:05:08 +10:00
parent 2fa3f14597
commit 2773d76e22
Signed by: blek
GPG Key ID: 14546221E3595D0C
5 changed files with 43 additions and 4 deletions

View File

@ -5,11 +5,12 @@
use std::collections::HashMap;
use warp::{Filter, reply::Reply, reject::Rejection, filters::multipart::FormData};
use askama::Template;
use warp::{Filter, reply::{Reply, Html}, reject::Rejection, filters::multipart::FormData, http::StatusCode, Error};
use futures_util::TryStreamExt;
use bytes::BufMut;
use super::state::SharedState;
use super::{state::SharedState, pages::BadActionReq, rejection::HttpReject};
pub async fn upload(form: FormData, _state: SharedState) -> Result<Box<dyn Reply>, Rejection> {
@ -20,7 +21,31 @@ pub async fn upload(form: FormData, _state: SharedState) -> Result<Box<dyn Reply
}
Ok((field.name().into(), String::from_utf8_lossy(&bytes).to_string()))
}).try_collect().await.unwrap();
}).try_collect()
.await
.map_err(|err| warp::reject::custom(HttpReject::WarpError(err.into())))?;
// check that required fields exist
let mut all_exist = true;
let _ = vec!["delmode", "file"].iter().for_each(|x| {
let field = x.to_string();
if ! params.contains_key(&field) {
all_exist = false;
}
});
if ! all_exist {
return Ok(Box::new(
warp::reply::with_status(
warp::reply::html(
BadActionReq {}
.render()
.map_err(|err| warp::reject::custom(HttpReject::AskamaError(err.into())))?
),
StatusCode::BAD_REQUEST
)
))
}
Ok(Box::new(warp::reply::json(&params)))
}

View File

@ -11,6 +11,7 @@ use crate::env::Env;
mod pages;
mod forms;
mod state;
mod rejection;
use state::SharedState;

View File

@ -9,7 +9,12 @@ use super::state::SharedState;
#[derive(Template)]
#[template( path = "index.html" )]
struct Index {}
pub struct Index {}
#[derive(Template)]
#[template( path = "bad_action_req.html" )]
pub struct BadActionReq {}
pub fn index() -> Html<String> {
let rendered = Index {};

View File

@ -0,0 +1,7 @@
#[derive(Debug)]
pub enum HttpReject {
WarpError(warp::Error),
AskamaError(askama::Error)
}
impl warp::reject::Reject for HttpReject {}

View File

@ -0,0 +1 @@
{% extends "base.html" %}