Skip to content

Commit

Permalink
add to_urlencoded_json
Browse files Browse the repository at this point in the history
  • Loading branch information
rawleyfowler committed Nov 15, 2022
1 parent 24caae6 commit a6ae75c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
15 changes: 15 additions & 0 deletions opium/src/request.ml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,21 @@ 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
`Assoc kv
;;

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 }
Expand Down
29 changes: 29 additions & 0 deletions opium/src/request.mli
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a6ae75c

Please sign in to comment.