0

What is the proper way to pass query string parameters to bs-fetch?

Currently, I have:

Fetch.fetch("https://example.com/api?param1=value1&param2=value2")

Obviously, this is not sustainable for larger parameter lists.

Is there a better way to do this?

glennsl
  • 28,186
  • 12
  • 57
  • 75
csb
  • 674
  • 5
  • 13

2 Answers2

2

i don't think there's something builtin for that. just make your own query builder function, something like this

let payload = Js.Dict.empty();

Js.Dict.set(payload, "email", Js.Json.string("email@email.co"));

Js.Dict.set(payload, "password", Js.Json.string("secret"));

let query =
  Js.Dict.keys(payload)
  |> Array.fold_left(
       (query, key) =>
         switch (Js.Dict.get(payload, key)) {
         | Some(value) =>
           query ++ key ++ "=" ++ Js.Json.stringify(value) ++ "&"
         | _ => query
         },
       "?"
     );

here's a link to the playground.

monssef
  • 1,006
  • 11
  • 12
2

re:fetch supports query params by way of either

request("https://example.com/api",
  ~queryParams=[
    ("param1", "value1"),
    ("param2", "value2")
  ])
|> fetch;

or

request("https://example.com/api")
|> Request.param("param1", "value1")
|> Request.param("param2", "value2")
|> fetch;

Beware that the library is experimental though. Alternatively, you could just swipe the query builder code, which has been battle-tested at least a little bit (there's a subtle bug in @monssef's implementation when there's an empty list, and it also doesn't do proper encoding):

[@bs.val] external encodeURIComponent : string => string = "";

let _buildUrl = (url, params) => {
  let encodeParam = ((key, value)) =>
    encodeURIComponent(key) ++ "=" ++ encodeURIComponent(value);

  let params =
      params |> List.map(encodeParam)
             |> String.joinWith("&");

  switch params {
  | "" => url
  | _ => {j|$url?$params|j}
  };
};
glennsl
  • 28,186
  • 12
  • 57
  • 75