Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom to construct a URI with a query string in Elixir

I'm wondering what the most idiomatic way is to use URI to add a query string to a base URI in Elixir.

I'm currently doing something like this:

iex(1)> base = "http://example.com/endpoint"
"http://example.com/endpoint"

iex(2)> query_string = URI.encode_query(foo: "bar")
"foo=bar"

iex(3)> uri_string = URI.parse(base) |> Map.put(:query, query_string) |> URI.to_string
"http://example.com/endpoint?foo=bar"

But was wondering if there is a cleaner way to set the query string. I know about URI.merge/2, but I don't think a query string is a valid URI, so that's probably not approriate here (the ? will not be added).

I could also do something like:

uri_string = %URI{ URI.parse(base) | query: query_string } |> URI.to_string

But I'm wondering if there is a simpler or clearer method I've missed.

like image 346
Adam Millerchip Avatar asked Mar 27 '18 08:03

Adam Millerchip


2 Answers

I think your first example, with some formatting, reads pretty well:

uri_string =
  base_url
  |> URI.parse()
  |> Map.put(:query, URI.encode_query(params))
  |> URI.to_string()

I'm not aware of other idioms/shortcuts.

like image 196
zwippie Avatar answered Nov 04 '22 18:11

zwippie


I'm not sure that it's more idiomatic but you can do simple string interpolation if you know the string you're trying to build.

uri_string = "#{base}?#{query_string}"
like image 42
Onorio Catenacci Avatar answered Nov 04 '22 18:11

Onorio Catenacci