Last active
September 19, 2015 07:59
-
-
Save nathanborror/67b894da36752c41cd30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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