From 9410e59e23a7b919272aacef26096f9169745778 Mon Sep 17 00:00:00 2001 From: Rawley Fowler Date: Tue, 15 Nov 2022 11:36:06 -0600 Subject: [PATCH] add to_urlencoded_json for request --- opium/src/request.ml | 17 +++++++++++++++++ opium/src/request.mli | 29 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/opium/src/request.ml b/opium/src/request.ml index 17be2fe8..5b035327 100644 --- a/opium/src/request.ml +++ b/opium/src/request.ml @@ -64,6 +64,23 @@ let to_urlencoded t = body |> Uri.query_of_encoded |> Lwt.return ;; +let to_urlencoded_json t = + let open Lwt.Syntax in + let+ body = to_urlencoded t in + let kv = + List.map + ~f:(function + | (k, [v]) -> (k, `String v) + | (k, xs) -> + let vs = List.map ~f:(fun t -> `String t) xs in + (k, `List vs)) + body + in + match kv with + | [] -> `Null + | xs -> `Assoc xs +;; + let header header t = Headers.get t.headers header let headers header t = Headers.get_multi t.headers header let add_header (k, v) t = { t with headers = Headers.add t.headers k v } diff --git a/opium/src/request.mli b/opium/src/request.mli index 1ff56af0..9cb21216 100644 --- a/opium/src/request.mli +++ b/opium/src/request.mli @@ -267,6 +267,35 @@ val to_json_exn : t -> Yojson.Safe.t Lwt.t {[ [ "username", [ "admin" ]; "password", [ "password" ] ] ]} *) val to_urlencoded : t -> (string * string list) list Lwt.t +(** [to_urlencoded_json t] parses the body of the request [t] from a urlencoded format to a json object. + + This function exist to offer a simple way to get all of the key-values pairs, but most + of the time, you'll probably only want the value of a key given. If you don't need the + entire list of values, it is recommended to use {!urlencoded} instead. + + If the body of the request cannot be parsed as a urlencoded string, [`Null] is + returned. + + {3 Example} + + {[ + let request = + Request.of_urlencoded + ~body:[ "username", [ "admin" ] + ; "password", [ "password" ] + ; "user_ids", [ "1"; "2"; "3" ] ] + "/" + `POST + ;; + + let values = Request.to_urlencoded_json request + ]} + + [values] will be: + + {[ { "username": "admin", "password": "password", "user_ids": [ "1", "2", "3"] } ]} *) +val to_urlencoded_json : t -> Yojson.Safe.t Lwt.t + (** {3 [to_multipart_form_data]} *) (** [to_multipart_form_data ?callback t] parses the body of the request [t] from a