# `Loopback.HTTPFake.Router`
[🔗](https://github.com/stefanchrobot/loopback/blob/v0.1.0/lib/loopback/http_fake/router.ex#L1)

A `Loopback.HTTPFake` with a routing DSL and helpers for the state.

    defmodule ExampleApiFake do
      use Loopback.HTTPFake.Router, match: "api.example.com"

      alias Loopback.HTTPResponse

      @impl true
      def init(_opts) do
        {:ok, %{items: %{}}}
      end

      get "/items/:id" do
        %{items: items} = get_state()

        case items[id] do
          nil -> HTTPResponse.json(404, %{"error" => "not found"})
          item -> HTTPResponse.json(200, item)
        end
      end

      post "/items" do
        id = Integer.to_string(System.unique_integer([:positive, :monotonic]))
        item = Map.put(JSON.decode!(request.body), "id", id)
        update_state(fn state -> put_in(state.items[id], item) end)
        HTTPResponse.json(201, item)
      end
    end

`Loopback.HTTPFake.Router` builds on top of `Loopback.HTTPFake` and supports the same
options.

## Routing

The routing DSL provides macros like `get/2` and `post/2`. For example:

    get "/items/:id" do
      HTTPResponse.json(200, %{id: id})
    end

compiles to roughly:

    def handle_route("GET", ["items", id], request) do
      HTTPResponse.json(200, %{id: id})
    end

See `get/2` for the syntax of the path, and the variables that a route gets.

`use Loopback.HTTPFake.Router` implements `c:Loopback.HTTPFake.handle_request/2`
by calling the routes:

    {:reply, handle_route(request.method, decode_path(request.url), request), state}

## Handling state

A fake gets the helpers `get_state/0,1`, `update_state/1` and `get_and_update_state/1`,
which work with the state like `Agent`'s functions:

    def trigger_downtime do
      update_state(fn state -> %{state | up?: false} end)
    end

These functions can be called both from routes and from test helpers. They're private,
so tests call the fake's public functions, like `trigger_downtime/0`.

## Preprocessing requests

The `c:before_route/1` callback runs before the routes, and can modify the request or stop
the processing:

    @impl true
    def before_route(request) do
      %{up?: up?} = get_state()

      if up? do
        {:cont, request}
      else
        {:halt, HTTPResponse.json(503, %{"error" => "down"})}
      end
    end

# `before_route`

```elixir
@callback before_route(request :: Loopback.HTTPFake.request()) ::
  {:cont, Loopback.HTTPFake.request()} | {:halt, Loopback.HTTPFake.reply()}
```

Runs before each request is routed.

Returns `{:cont, request}` to route the request, or `{:halt, reply}` to reply without
routing it, for example to simulate an outage. The returned request is the one that's
routed, so it can be transformed for all the routes. Defaults to `{:cont, request}`.

# `handle_route`

```elixir
@callback handle_route(
  method :: String.t(),
  path :: [String.t()],
  request :: Loopback.HTTPFake.request()
) ::
  Loopback.HTTPFake.reply()
```

Handles a request, routed by its method and path.

The path is the list of the URL's path segments, URI-decoded, so `/items/a%20b` is
`["items", "a b"]`. The host and the query aren't part of the route, `request.url` has
them.

Returns the reply, see `t:Loopback.HTTPFake.reply/0`. A request that no clause matches
crashes the fake with an error that names the request's method and URL.

# `delete`
*macro* 

Defines a route for `DELETE` requests, like `get/2`.

# `get`
*macro* 

Defines a route for `GET` requests to the path.

Generates a clause of `c:handle_route/3`, which is matched against the request's method
and path segments. For example:

    get "/items/:id" do
      %{items: items} = get_state()

      case items[id] do
        nil -> Loopback.HTTPResponse.new(status: 404)
        item -> Loopback.HTTPResponse.json(200, item)
      end
    end

compiles to roughly:

    def handle_route("GET", ["items", id], request) do
      %{items: items} = get_state()
      # ...
    end

The path's segments are literals, like `items`, or path params, like `:id`, which the
route's body gets as variables, along with the request as `request`. The last segment can
also be a glob, like `*rest`, which matches the remaining segments, so
`get "/files/*rest"` is `def handle_route("GET", ["files" | rest], request)`.

The route returns the reply, see `t:Loopback.HTTPFake.reply/0`. Routes match in the order
they're defined.

# `head`
*macro* 

Defines a route for `HEAD` requests, like `get/2`.

# `options`
*macro* 

Defines a route for `OPTIONS` requests, like `get/2`.

# `patch`
*macro* 

Defines a route for `PATCH` requests, like `get/2`.

# `post`
*macro* 

Defines a route for `POST` requests, like `get/2`.

# `put`
*macro* 

Defines a route for `PUT` requests, like `get/2`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
