AlexCouch / pluvo

Pluvo is a modern web framework purely in Gleam built ontop of mist
4 stars 0 forks source link

Middleware functions cannot be made with more than 1 hole #11

Closed AlexCouch closed 8 months ago

AlexCouch commented 8 months ago

Description

Middleware config functions return a partial function (captured function) of the middleware function with the config. However, I didn't realize that partial functions can only have one hole.

Solution

Middleware must be given an auxiliary middleware context with which the middleware can destructure the route and context objects.

pub fn cors_mw(_config: CORSConfig, ctx: MiddlewareContext) -> Response{
    let MWContext(route, ctx) = ctx

    ctx 
    |> route.method.handler
}

pub fn cors(config: CORSConfig) -> Middleware{
    cors_mw(config, _)
}
AlexCouch commented 8 months ago

As of 23bd320, a basic CORS middleware works but still needs work and a better test. It at least is called, and I was able to rework the middleware a bit so that a middleware func takes a route handler and returns another route handler.

pub fn cors_mw(config: CORSConfig, handler: route.RouteHandler) -> route.RouteHandler{
    let allowed_headers = config.allowed_headers
    |> string.join(",")

    let allowed_origins = {
        use <- util.when(list.is_empty(config.allowed_origins), default_config.allowed_origins |> string.join(","))
        config.allowed_origins
        |> string.join(",")
    }

    fn(ctx: Context)->Response{
        ctx
        |> context.set_header(allow_access_headers, allowed_headers)
        |> context.set_header(allow_access_origins, allowed_origins)
        |> handler
    }
}