Skip to content

Commit

Permalink
Add a scope function in Router
Browse files Browse the repository at this point in the history
  • Loading branch information
tmattio committed Jun 1, 2020
1 parent b43f9d6 commit e0e9286
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
9 changes: 9 additions & 0 deletions opium_kernel/middlewares/router.ml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,15 @@ let splat req =
Hmap0.find_exn Env.key req.Rock.Request.env |> fun route -> route.Route.splat
;;

let scope ~route ~middlewares router routes =
ListLabels.iter routes ~f:(fun (meth, subroute, action) ->
let action =
ListLabels.fold_left middlewares ~init:action ~f:(fun h m ->
Rock.Middleware.apply m h)
in
add router ~action ~meth ~route:(Route.of_string (Filename.concat route subroute)))
;;

let m endpoints =
let filter default req =
let url = req.Rock.Request.target in
Expand Down
29 changes: 29 additions & 0 deletions opium_kernel/opium_kernel.mli
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,35 @@ module Router : sig
val add : 'a t -> route:Route.t -> meth:Httpaf.Method.standard -> action:'a -> unit
val param : Rock.Request.t -> string -> string
val splat : Rock.Request.t -> string list

(** [scope] adds scoped routes to the router.
The scoped routes will be prefixed by [route] and their handlers will be wrapped by
[middlewares].
{4 Example}
Here's an example that defines a scope that will prefix every routes with "/users"
and will wrap the handlers with a middleware defined in [Middleware.require_auth].
{[
let () =
Router.scope
~middlewares:[ Middleware.require_auth ]
~route:"/users"
router
[ `POST, "/register", Handlers.register_user
; `POST, "/login", Handlers.login_user
]
;;
]} *)
val scope
: route:string
-> middlewares:Rock.Middleware.t list
-> Rock.Handler.t t
-> (Httpaf.Method.standard * string * Rock.Handler.t) list
-> unit

val m : Rock.Handler.t t -> Rock.Middleware.t
end

Expand Down

0 comments on commit e0e9286

Please sign in to comment.