Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Last active September 19, 2015 07:59
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 nathanborror/67b894da36752c41cd30 to your computer and use it in GitHub Desktop.
Save nathanborror/67b894da36752c41cd30 to your computer and use it in GitHub Desktop.
defmodule Nthn.Entry.Handler do
import Ecto.Query
alias Nthn.Entry
alias Nthn.Repo
def init({:tcp, :http}, req, opts) do
{:ok, req, opts}
end
def handle(req, state) do
{method, req} = :cowboy_req.method(req)
{param, req} = :cowboy_req.binding(:id, req)
contenttype = {"content-type", "application/json; charset=utf-8"}
{:ok, resp} = resource(String.to_atom(method), param, req)
{:ok, reply} = :cowboy_req.reply(200, [contenttype], resp, req)
{:ok, reply, state}
end
def resource(:GET, :undefined, _req) do
results = Entry |> Repo.all |> Poison.encode! pretty: true
{:ok, results}
end
def resource(:GET, param, _req) do
result = Entry |> where([entry], entry.id == ^param) |> Repo.all |> Poison.encode! pretty: true
{:ok, result}
end
def resource(:POST, :undefined, req) do
{:ok, body, req} = :cowboy_req.body(req)
{:ok, entry} = Poison.decode!(body, as: Entry) |> Repo.insert
{host_url, _req} = :cowboy_req.host_url(req)
{:ok, "#{host_url}/entries/#{entry.id}"}
end
def resource(:PUT, param, req) do
{:ok, nil}
end
def resource(:DELETE, param, req) do
{:ok, nil}
end
def terminate(reason, _req, _state) do
IO.puts("Terminating: #{inspect(reason)}")
:ok
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment