Skip to content

Commit

Permalink
rename cursor functions, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
woylie committed Oct 7, 2020
1 parent cf54896 commit 5145923
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 8 deletions.
2 changes: 1 addition & 1 deletion lib/flop.ex
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ defmodule Flop do
defp apply_cursor(q, nil, _), do: q

defp apply_cursor(q, cursor, ordering) do
cursor = Cursor.decode_cursor(cursor)
cursor = Cursor.decode(cursor)

Enum.reduce(ordering, q, fn {direction, field}, q ->
case direction do
Expand Down
16 changes: 10 additions & 6 deletions lib/flop/cursor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ defmodule Flop.Cursor do
Encodes a cursor value.
"""
@doc since: "0.8.0"
@spec encode_cursor(map()) :: binary()
def encode_cursor(key) do
@spec encode(map()) :: binary()
def encode(key) do
Base.url_encode64(:erlang.term_to_binary(key))
end

@doc """
Decodes a cursor value.
"""
@doc since: "0.8.0"
@spec decode_cursor(binary()) :: map()
def decode_cursor(encoded) do
@spec decode(binary()) :: map()
def decode(encoded) do
encoded
|> Base.url_decode64!()
|> :erlang.binary_to_term([:safe])
Expand All @@ -43,6 +43,10 @@ defmodule Flop.Cursor do
|> Enum.reduce({}, &Tuple.append(&2, &1))
end

defp sanitize(_) do
raise "invalid cursor value"
end

@doc """
Retrieves the start and end cursors from a query result.
"""
Expand All @@ -58,11 +62,11 @@ defmodule Flop.Cursor do

[first | _] ->
{
first |> get_cursor_value_func.(order_by) |> encode_cursor(),
first |> get_cursor_value_func.(order_by) |> encode(),
results
|> List.last()
|> get_cursor_value_func.(order_by)
|> encode_cursor()
|> encode()
}
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/flop/relay.ex
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,6 @@ defmodule Flop.Relay do
end

defp get_cursor(node, order_by, get_cursor_value_func) do
node |> get_cursor_value_func.(order_by) |> Cursor.encode_cursor()
node |> get_cursor_value_func.(order_by) |> Cursor.encode()
end
end
20 changes: 20 additions & 0 deletions test/flop/cursor_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
defmodule Flop.CursorTest do
use ExUnit.Case, async: true

alias Flop.Cursor

describe "encoding/decoding" do
test "encoding and decoding returns original value" do
value = %{a: "b", c: [:d], e: {:f, "g", 5}}
assert value |> Cursor.encode() |> Cursor.decode() == value
end

test "cursor value containing function results in error" do
value = %{a: fn b -> b * 2 end}

assert_raise RuntimeError, fn ->
value |> Cursor.encode() |> Cursor.decode()
end
end
end
end

0 comments on commit 5145923

Please sign in to comment.