Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add to_urlencoded_json to request #287

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions opium/src/request.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
| [] -> None
| xs -> Some (`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 }
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, [None] 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 option Lwt.t

(** {3 [to_multipart_form_data]} *)

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