summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMateus Cruz <mateuscolvr@gmail.com>2024-02-05 00:14:45 -0300
committerMateus Cruz <mateuscolvr@gmail.com>2024-02-05 00:42:06 -0300
commitf0142aa1c3b4d7c2fd0b70c9e62c1ec033e445c2 (patch)
tree7f979459a60365f16197889d2ec660847141d42a /lib
parentf3ac99a84497868aded8ee7ec2822d1b12960fd7 (diff)
add basic route handling
Diffstat (limited to 'lib')
-rw-r--r--lib/dune3
-rw-r--r--lib/router.ml59
-rw-r--r--lib/router.mli1
3 files changed, 62 insertions, 1 deletions
diff --git a/lib/dune b/lib/dune
index 45a8131..837c7b7 100644
--- a/lib/dune
+++ b/lib/dune
@@ -1,2 +1,3 @@
(library
- (name rinhadebackend))
+ (name rinha)
+ (libraries piaf routes yojson))
diff --git a/lib/router.ml b/lib/router.ml
new file mode 100644
index 0000000..cbff9fb
--- /dev/null
+++ b/lib/router.ml
@@ -0,0 +1,59 @@
+[@@@warning "-26-27-32"]
+
+open StdLabels
+open Routes
+open Piaf
+
+module R = Map.Make (struct
+ type t = Method.t
+
+ let compare a b =
+ let a_str = Method.to_string a in
+ let b_str = Method.to_string b in
+ String.compare a_str b_str
+ ;;
+ end)
+
+let transactions_route =
+ let handler client_id (request : Request.t) =
+ let json : Yojson.Safe.t = `Assoc [ "limite", `Int 100000; "saldo", `Int (-9098) ] in
+ Response.of_string ~body:(Yojson.Safe.to_string json) `OK
+ in
+ (s "clientes" / int / s "transacoes" /? nil) @--> handler
+;;
+
+let balance_route =
+ let handler client_id (request : Request.t) =
+ let json : Yojson.Safe.t =
+ let balance =
+ let total = `Int (-9098) in
+ let date = `String "2024-01-17T02:34:41.217753Z" in
+ let limit = `Int 100000 in
+ `Assoc [ "total", total; "data_extrato", date; "limite", limit ]
+ in
+ let last_transactions = `List [] in
+ `Assoc [ "saldo", balance; "ultimas_transacoes", last_transactions ]
+ in
+ Response.of_string ~body:(Yojson.Safe.to_string json) `OK
+ in
+ (s "clientes" / int / s "extrato" /? nil) @--> handler
+;;
+
+let routes =
+ List.fold_left
+ ~f:(fun acc (v, r) -> R.add_to_list v r acc)
+ [ `GET, balance_route; `POST, transactions_route; `POST, balance_route ]
+ ~init:R.empty
+;;
+
+let router = R.map one_of routes
+
+let match_route verb path =
+ match R.find_opt verb router with
+ | Some router ->
+ (match match' router ~target:path with
+ | FullMatch r -> Some r
+ | MatchWithTrailingSlash r -> Some r
+ | NoMatch -> None)
+ | None -> None
+;;
diff --git a/lib/router.mli b/lib/router.mli
new file mode 100644
index 0000000..c0b5915
--- /dev/null
+++ b/lib/router.mli
@@ -0,0 +1 @@
+val match_route : Piaf.Method.t -> string -> (Piaf.Request.t -> Piaf.Response.t) option