Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Router scope #150

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions opium_kernel/src/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 =
match matching_endpoint endpoints req.Rock.Request.meth req.Rock.Request.target with
Expand Down
29 changes: 29 additions & 0 deletions opium_kernel/src/opium_kernel.mli
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,35 @@ module Router : sig
val add : 'a t -> route:Route.t -> meth:Httpaf.Method.t -> action:'a -> 'a t
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