robertwayne / axum-htmx

A set of htmx extractors, responders, and request guards for axum.
Apache License 2.0
185 stars 9 forks source link

Fallible extractors #23

Open jonahlund opened 2 weeks ago

jonahlund commented 2 weeks ago

Having infallible extractors makes them less flexible, it's generally better to let the user decide if they want the extraction to fail or not, especially considering the fact that you can use the Option extractor for any infallible extractions, i.e:

Option::<HxTarget>::from_request_parts(..)
jonahlund commented 2 weeks ago

If you aren't convinced, consider this, say I want to write my custom extractor wrapping HxTarget, this is how I would want to write it:

pub enum MyTarget {
    SomeTarget,
    OtherTarget,
}

impl FromStr for MyTarget { .. }

impl FromRequestParts<AppState> for MyTarget {
    type Rejection = Error;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let HxTarget(target) = HxTarget::from_request_parts(parts, state).await?;

        Ok(target.parse()?)
    }
}

Then if I wanted to do an infallible extraction here I would just do

Option::<MyTarget>::from_request_parts(..)

But since HxTarget is always infallible, I have to explicitly handle the case where it might be None even though we just want to propagate whatever error the extraction would return in case the header wasn't present.

It basically breaks the chain of extractors by having an infallible extractor that otherwise could be considered fallible.