Skip to content

Instantly share code, notes, and snippets.

@lightningspirit
Created February 6, 2018 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lightningspirit/a7e7c8723365df255cac1a88ec82fc5c to your computer and use it in GitHub Desktop.
Save lightningspirit/a7e7c8723365df255cac1a88ec82fc5c to your computer and use it in GitHub Desktop.
Hal representers lib prototype

Hal representers for Elixir

Have JSON/Hal representers for your modules

Library idea

lib/hal/hal.ex:

defmodule APIWeb.Hal.Assignment
  def property
    ...
  end
  
  def link
    ...
  end
  
  def embedded
    ...
  end
end
defmodule APIWeb.Hal.Assignment
import Hal
import APIWeb.Router.Helpers
alias APIWeb.Endpoint
property :id
property :status
property :created_at
property :updated_at
property :attribute_set
property :priority
property :min_results
property :max_results
property :timeout
property :strategy
link :assignment, assignment_url(Endpoint, :show, :assignment_id)
end
{:ok, assignments} ->
conn
|> hal(%{
total: length(assignments),
page: pagination["page"],
per_page: pagination["per_page"],
assignments: assignments,
prev_page: job_url(Endpoint, :index, page: prev_page, per_page: per_page),
next_page: job_url(Endpoint, :index, page: next_page, per_page: per_page),
})
defmodule APIWeb.Hal.Assignments
import Hal
import APIWeb.Router.Helpers
alias APIWeb.Endpoint
property :total
property :page
property :per_page
embedded %{
jobs: assignments
}
if (next_page)
link :next, next_page
end
if (prev_page)
link :prev, prev_page
end
end
defmodule APIWeb.Router do
use APIWeb, :router
alias APIWeb.Plug.{ApiKey, AccountID}
pipeline :api do
plug :accepts, ["json"]
plug ApiKey
plug AccountID
end
scope "/", APIWeb do
pipe_through :api
resources "/interactions", InteractionController do
resources "/assignments", AssignmentController do
resources "/jobs", JobsController
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment