ocaml-uri
ocaml-uri copied to clipboard
Convenience functions for extracting multiple arguments
trafficstars
Pulling from https://github.com/rgrinberg/opium/issues/32#issuecomment-73842718 it would be nice to have a function for extracting multiple query parameters with a single call, similar to:
(* only match if all query params are present *)
val get_query_params : Uri.t -> string list -> (string list list) option
(* allow for partial matches of parameters list *)
val get_query_params' : Uri.t -> string list -> (string list option) list
usable as:
match get_query_params uri ["ua"; "xx"; "yyy"] with
| Some [ua; xx; yyy] -> ...
| _ -> ...
or, if you're expecting and want to only accept a single argument for a parameter:
match get_query_params uri ["ua"; "xx"; "yyy"] with
| Some [[ua]; [xx]; yyy] -> ... (* Only match if ua and xx are single-valued, yyy gets everything *)
| _ -> ...
This is an API to consider for the fabled 2.0 release.
An mostly untested implementation if someone wants something before 2.0:
let get_query_params uri keys =
let values = List.map (fun k -> Uri.get_query_param' uri k) keys in
let result =
List.fold_left (
fun accu mayv ->
match accu, mayv with
| None, _ -> None
| _, None -> None
| Some l, Some v -> Some (v :: l)
) (Some []) values
in
match result with
| None -> None
| Some l -> Some (List.rev l)
let get_query_params' uri keys =
List.map (fun k -> Uri.get_query_param' uri k) keys