Condition - Simple

In this example, we’re going to add a condition that asserts the foo param does not equal "bar".

Setup

We start by creating a resource and adding the condition/1 call

defmodule Foo do
  use(Mazurka.Resource)

  param(foo)

  condition(foo != "bar")

  mediatype(Hyper) do
    action() do
      %{"foo" => foo}
    end
  end
end

We’ll also set up a router so we can observe how affordances work with failed conditions.

defmodule Router do
  def(resolve(%{resource: Foo, params: %{"foo" => foo}} = affordance, _source, _conn)) do
    %{affordance | method: "GET", path: "/foo/#{foo}"}
  end
end

Action success

Here we pass the value of "baz" for the "foo" param.

This call should return successfully.

accepts = [{"application", "hyper+json", %{}}]
params = %{"foo" => "baz"}
input = %{}
conn = %{}
{response, content_type, _conn} = Foo.action(accepts, params, input, conn, Router)
%{"foo" => "baz"} = response
{"application", "hyper+json", _} = content_type

Action failure

In this case we’ll pass "bar" as the "foo" param and we should get a Mazurka.ConditionException.

assert_raise(Mazurka.ConditionException, fn ->
  accepts = []
  params = %{"foo" => "bar"}
  input = %{}
  conn = %{}
  Foo.action(accepts, params, input, conn)
end)

Affordance success

When we call the Foo.affordance/5 function with valid params we get a valid affordance.

accepts = [{"application", "hyper+json", %{}}]
params = %{"foo" => "baz"}
input = %{}
conn = %{}
{affordance, content_type} = Foo.affordance(accepts, params, input, conn, Router)
%{"href" => "/foo/baz"} = affordance
{"application", "hyper+json", _} = content_type

Affordance failure

When calling an affordance with invalid data we’ll get a Mazurka.Affordance.Undefined struct informing us that the affordance was unable to render.

accepts = [{"application", "hyper+json", %{}}]
params = %{"foo" => "bar"}
input = %{}
conn = %{}
{affordance, _} = Foo.affordance(accepts, params, input, conn, Router)
%Mazurka.Affordance.Undefined{} = affordance