PlugHTTPValidator

Set HTTP validators to Plug responses

When and why use it

As soon as you send cacheable content, you should set HTTP validators because it helps HTTP caches a lot:

There are two HTTP validators:

Although using a strong validator is to be preferred (more optimisations possible), it is not always possible because you need a unique identifier for each revision of your objects (e.g database entries). For instance, this is hard to achieve with Ecto.

However, using a weak validator like last-modified is very helpful for caches as well, so do it!

Usage

PlugHTTPValidator.set/3 sets HTTP validators using the object(s) passed into parameter.

Call it before sending the response, for example:

def index(conn, _params) do
  posts = MyApp.list_posts()

  conn
  |> PlugHTTPValidator.set(posts)
  |> render("index.json", posts: posts)
end

def create(conn, params) do
  # 201 status code is not cacheable by default

  with {:ok, post} <- MyApp.create_post(params) do
    conn
    |> put_status(:created)
    |> put_resp_header("location", Routes.post_path(conn, :show, post))
    |> render("show.json", post: post)
  end
end

def show(conn, %{"id" => id}) do
  with {:ok, post} = MyApp.get_post(id) do
    conn
    |> PlugHTTPValidator.set(post)
    |> render("show.txt", post: post)
  end
end

By default, this function sets the last-modified response header using the :updated_at field of the object(s), taking the most recent if there are more than one object.

Options

Installation

def deps do
  [
    {:plug_http_validator, "~> 0.1.0"}
  ]
end

This plug was inspired by phoenix_etag, which seems outdated.