raxx v0.8.0 URI2.Query

Utilities for working with url query strings.

Namespaced under URI2 as it is a replacement for the native URI module. Calls the original module until the query API is finalised.

All functions are pure, They return try tuples when there is a possibility of failure

Summary

Functions

Use bracket notation for nested queries

Decode a query string into a nested map of values

Returns the query as a list of keyvalue pairs

Functions

build_nested(key_value_pairs, nested \\ %{})

Use bracket notation for nested queries.

Note this is not a formal part of the query specification.

Examples

iex> URI2.Query.build_nested([{"foo", "1"}, {"bar", "2"}])
{:ok, %{"foo" => "1", "bar" => "2"}}

iex> URI2.Query.build_nested([{"foo[]", "1"}, {"foo[]", "2"}])
{:ok, %{"foo" => ["1", "2"]}}

iex> URI2.Query.build_nested([{"foo[bar]", "1"}, {"foo[baz]", "2"}])
{:ok, %{"foo" => %{"bar" => "1", "baz" => "2"}}}

iex> URI2.Query.build_nested([{"foo[bar][baz]", "1"}])
{:ok, %{"foo" => %{"bar" => %{"baz" => "1"}}}}

iex> URI2.Query.build_nested([{"foo[bar][]", "1"}, {"foo[bar][]", "2"}])
{:ok, %{"foo" => %{"bar" => ["1", "2"]}}}

# I think this case does not work because it is ambiguous whether the second kv item should be added to the first list item.
# iex> URI2.Query.build_nested([{"foo[][bar]", "1"}, {"foo[][baz]", "2"}])
# {:ok, %{"foo" => [%{"bar" => "1"}, %{"baz" => "2"}]}}
decode(query_string)

Decode a query string into a nested map of values

iex> URI2.Query.decode("percentages[]=15&percentages[]=99+%21")
{:ok, %{"percentages" => ["15", "99 !"]}}
parse(query_string)

Returns the query as a list of keyvalue pairs.

This parsing looses no information

Examples

iex> URI2.Query.parse("foo=1&bar=2")
{:ok, [{"foo", "1"}, {"bar", "2"}]}

iex> URI2.Query.parse("%ZZ")
{:error, :invalid_query}

Directly using URI.decode_next_query_pair/1 is not possible as it is private