Skip to content

Commit a6ae75c

Browse files
committed
add to_urlencoded_json
1 parent 24caae6 commit a6ae75c

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

opium/src/request.ml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,21 @@ let to_urlencoded t =
6464
body |> Uri.query_of_encoded |> Lwt.return
6565
;;
6666

67+
let to_urlencoded_json t =
68+
let open Lwt.Syntax in
69+
let+ body = to_urlencoded t in
70+
let kv =
71+
List.map
72+
~f:(function
73+
| (k, [v]) -> (k, `String v)
74+
| (k, xs) ->
75+
let vs = List.map ~f:(fun t -> `String t) xs in
76+
(k, `List vs))
77+
body
78+
in
79+
`Assoc kv
80+
;;
81+
6782
let header header t = Headers.get t.headers header
6883
let headers header t = Headers.get_multi t.headers header
6984
let add_header (k, v) t = { t with headers = Headers.add t.headers k v }

opium/src/request.mli

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,35 @@ val to_json_exn : t -> Yojson.Safe.t Lwt.t
267267
{[ [ "username", [ "admin" ]; "password", [ "password" ] ] ]} *)
268268
val to_urlencoded : t -> (string * string list) list Lwt.t
269269

270+
(** [to_urlencoded_json t] parses the body of the request [t] from a urlencoded format to a json object.
271+
272+
This function exist to offer a simple way to get all of the key-values pairs, but most
273+
of the time, you'll probably only want the value of a key given. If you don't need the
274+
entire list of values, it is recommended to use {!urlencoded} instead.
275+
276+
If the body of the request cannot be parsed as a urlencoded string, [`Null] is
277+
returned.
278+
279+
{3 Example}
280+
281+
{[
282+
let request =
283+
Request.of_urlencoded
284+
~body:[ "username", [ "admin" ]
285+
; "password", [ "password" ]
286+
; "user_ids", [ "1"; "2"; "3" ] ]
287+
"/"
288+
`POST
289+
;;
290+
291+
let values = Request.to_urlencoded_json request
292+
]}
293+
294+
[values] will be:
295+
296+
{[ { "username": "admin", "password": "password", "user_ids": [ "1", "2", "3"] } ]} *)
297+
val to_urlencoded_json : t -> Yojson.Safe.t Lwt.t
298+
270299
(** {3 [to_multipart_form_data]} *)
271300

272301
(** [to_multipart_form_data ?callback t] parses the body of the request [t] from a

0 commit comments

Comments
 (0)