diff options
author | Mateus Cruz <mateuscolvr@gmail.com> | 2024-02-05 11:06:46 -0300 |
---|---|---|
committer | Mateus Cruz <mateuscolvr@gmail.com> | 2024-02-05 11:06:46 -0300 |
commit | 8878b1d92bdd8ee9b51ecde7e9cc88f62f264841 (patch) | |
tree | 46d6c47dfc820689baa552d97255adeda4c98b15 /lib/handler.ml | |
parent | 5a2f5bf9a12b270e15757df48afeb1c1db5b34b3 (diff) |
move routes handler module to its own file
Diffstat (limited to 'lib/handler.ml')
-rw-r--r-- | lib/handler.ml | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/lib/handler.ml b/lib/handler.ml new file mode 100644 index 0000000..4ee7189 --- /dev/null +++ b/lib/handler.ml @@ -0,0 +1,63 @@ +open Piaf + +let create_transaction client_id (db_pool : Query.pool) (request : Request.t) = + Caqti_eio.Pool.use + (fun conn -> + let client_opt = + Option.join @@ Result.to_option @@ Query.find_client client_id conn + in + match client_opt with + | Some _client -> + let insert_result = + let body = Result.to_option @@ Body.to_string request.body in + let json = Option.map Yojson.Safe.from_string body in + let decoded_op = Option.bind json (Utils.Decoder.decode Operation.decoder) in + match decoded_op with + | Some op -> + (match Query.execute_operation ~client_id ~op conn with + | Ok _ as ok -> ok + | Error e -> Error (`DB e)) + | None -> Error (`Decoder "Invalid operation") + in + (match insert_result with + | Ok () -> + let json : Yojson.Safe.t = + `Assoc [ "limite", `Int 100000; "saldo", `Int (-9098) ] + in + Ok (Response.of_string ~body:(Yojson.Safe.to_string json) `OK) + | Error _ -> Ok (Response.create (`Code 422))) + | None -> Ok (Response.create `Not_found)) + db_pool +;; + +let get_balance client_id (db_pool : Query.pool) (_request : Request.t) = + Caqti_eio.Pool.use + (fun conn -> + let client_opt = + Option.join @@ Result.to_option @@ Query.find_client client_id conn + in + match client_opt with + | Some _client -> + let client_balance_opt = + Option.join @@ Result.to_option @@ Query.balance client_id conn + in + (match client_balance_opt with + | Some (balance_value, time) -> + let json : Yojson.Safe.t = + let balance = + let total = `Int balance_value in + let date = + `String + (Format.asprintf "%a" (Ptime.pp_rfc3339 ~tz_offset_s:(-10800) ()) time) + 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 + Ok (Response.of_string ~body:(Yojson.Safe.to_string json) `OK) + | None -> Ok (Response.create `Not_found)) + | None -> Ok (Response.create `Not_found)) + db_pool +;; |