@@ -10,54 +10,48 @@ module Method_map = Map.Make (struct
1010 ;;
1111end )
1212
13- type t = ( Route .t * Rock.Handler .t ) list Method_map .t
13+ type t = Rock.Handler .t Method_map .t Router .t
1414
15- let empty = Method_map . empty
15+ let empty = Router . empty
1616
17- let get t meth =
18- match Method_map. find_opt meth t with
19- | None -> []
20- | Some xs -> List. rev xs
21- ;;
22-
23- let add t ~route ~meth ~action =
24- Method_map. update
25- meth
26- (function
27- | None -> Some [ route, action ]
28- | Some xs -> Some ((route, action) :: xs))
29- t
17+ let add (t : t ) ~route ~meth ~action =
18+ Router. update t route ~f: (function
19+ | None -> Method_map. singleton meth action
20+ | Some m -> Method_map. add meth action m)
3021;;
3122
3223(* * finds matching endpoint and returns it with the parsed list of parameters *)
33- let matching_endpoint endpoints meth uri =
34- let endpoints = get endpoints meth in
35- List. find_map endpoints ~f: (fun ep ->
36- uri |> Route. match_url (fst ep) |> Option. map (fun p -> ep, p))
24+ let matching_endpoint (endpoints : t ) meth uri =
25+ match Router. match_url endpoints uri with
26+ | None -> None
27+ | Some (a , params ) ->
28+ (match Method_map. find_opt meth a with
29+ | None -> None
30+ | Some h -> Some (h, params))
3731;;
3832
3933module Env = struct
40- let key : Route.matches Context.key =
41- Context.Key. create (" path_params" , Route. sexp_of_matches )
34+ let key : Router.Params.t Context.key =
35+ Context.Key. create (" path_params" , Router.Params. sexp_of_t )
4236 ;;
4337end
4438
45- let splat req = Context. find_exn Env. key req.Request. env |> fun route -> route. Route. splat
39+ let splat req = Context. find_exn Env. key req.Request. env |> Router.Params. unnamed
4640
4741(* not param_exn since if the endpoint was selected it's likely that the parameter is
4842 already there *)
4943let param req param =
50- let { Route. params; _ } = Context. find_exn Env. key req.Request. env in
51- List. assoc param params
44+ let params = Context. find_exn Env. key req.Request. env in
45+ Router.Params. named params param
5246;;
5347
5448let m endpoints =
5549 let filter default req =
5650 match matching_endpoint endpoints req.Request. meth req.Request. target with
5751 | None -> default req
58- | Some (endpoint , params ) ->
52+ | Some (handler , params ) ->
5953 let env_with_params = Context. add Env. key params req.Request. env in
60- (snd endpoint) { req with Request. env = env_with_params }
54+ handler { req with Request. env = env_with_params }
6155 in
6256 Rock.Middleware. create ~name: " Router" ~filter
6357;;
0 commit comments