AlexCouch / pluvo

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

Put route parameters into `RouteMethod.param_names` and remove `Context` from router #2

Closed AlexCouch closed 10 months ago

AlexCouch commented 10 months ago

As per #1, the router is given a context object, which is then updated with the request parameters, but this is a bit silly. We have a RouteMethod for a reason.

pub fn get_route(ctx: Context, router: Router, path: String) -> Option(RouteContext){
    let path = path 
    |> path.from_string

    let route = path
    |> get_lcp(router.tree)
    |> option.map(fn(path){
        dict.get(router.routes, path)
        |> option.from_result
    })
    |> option.flatten

    //This is what we wanna get rid of
    use route <- option.then(route)
    use param <- option.then(get_param(route, path))
    let ctx = ctx 
    |> context.add_param(param.name, param.value)

    RouteContext(route, ctx)
    |> Some
}

So that we can have it look more like this, like it was before

pub fn get_route(ctx: Context, router: Router, path: String) -> Option(Route){
    let path = path 
    |> path.from_string

    let route = path
    |> get_lcp(router.tree)
    |> option.map(fn(path){
        dict.get(router.routes, path)
        |> option.from_result
    })
    |> option.flatten
}

The only difference is that we move the storage of the request parameters to the route's RouteMethod instance, which actually simplifies the code a lot.

AlexCouch commented 10 months ago

The final code for get_route is almost the same as above, the only difference is I've added an extra function to get the params into the header.

pub fn get_route(router: Router, path: String) -> Option(Route){
    let path = path 
    |> path.from_string

    path
    |> get_lcp(router.tree)
    |> option.map(fn(path){
        dict.get(router.routes, path)
        |> option.from_result
    })
    |> option.flatten
    |> add_params(path)
}