Search code examples
fetch-apireasonbucklescript

How to pass query string parameters with bs-fetch?


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?


Solution

  • 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}
      };
    };