Skip to content

Commit

Permalink
feat: allow custom patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
anuragsoni committed Jan 20, 2020
1 parent d74e718 commit f9f39dc
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,48 @@ val print_route : int -> string = <fun>
- : string = "user/12/add"
```

It is possible to define custom patterns that can be used for matching.

```ocaml
# open Routes;;
# type shape = Circle | Square
type shape = Circle | Square
# let shape_of_string = function "circle" -> Some Circle | "square" -> Some Square | _ -> None
val shape_of_string : string -> shape option = <fun>
# let shape_to_string = function Circle -> "circle" | Square -> "square"
val shape_to_string : shape -> string = <fun>
# let shape = pattern shape_to_string shape_of_string
val shape : ('_weak1, '_weak2) path -> (shape -> '_weak1, '_weak2) path =
<fun>
# let process_shape (s : shape) = shape_to_string s
val process_shape : shape -> string = <fun>
# let route () = s "shape" / shape / s "create" /? nil
val route : unit -> (shape -> '_weak3, '_weak3) path = <fun>
# sprintf route
- : shape -> string = <fun>
# sprintf route Square
- : string = "shape/square/create"
# let router = one_of [ None, route @--> process_shape ]
val router : string router = <abstr>
# match' ~target:"/shape/circle/create" router
- : string option = Some "circle"
# match' ~target:"/shape/square/create" router
- : string option = Some "square"
# match' ~target:"/shape/triangle/create" router
- : string option = None
```

## Installation

###### To use the version published on opam:
Expand Down
1 change: 1 addition & 0 deletions src/routes.ml
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ type 'b router =
; any_method : 'b route PatternTrie.t
}

let pattern to_ from_ r = Conv (conv to_ from_, r)
let empty_router = { method_routes = Method.M.empty; any_method = PatternTrie.empty }
let ( @--> ) r handler = Route (r (), handler)
let s w r = Match (w, r)
Expand Down
6 changes: 6 additions & 0 deletions src/routes.mli
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ type ('a, 'b) path
type 'b route
type 'b router

val pattern
: ('c -> string)
-> (string -> 'c option)
-> ('a, 'b) path
-> ('c -> 'a, 'b) path

val int : ('a, 'b) path -> (int -> 'a, 'b) path
val int32 : ('a, 'b) path -> (int32 -> 'a, 'b) path
val int64 : ('a, 'b) path -> (int64 -> 'a, 'b) path
Expand Down

0 comments on commit f9f39dc

Please sign in to comment.