Skip to content

Instantly share code, notes, and snippets.

@spiegela
Last active December 27, 2015 15:28
Show Gist options
  • Select an option

  • Save spiegela/7347480 to your computer and use it in GitHub Desktop.

Select an option

Save spiegela/7347480 to your computer and use it in GitHub Desktop.
Possible API for developing RESTful routes & handlers in Dynamo
defmodule FruitCollectionHandler do
use Dynamo.RESTHandler
allowed_methods ["GET", "POST", "OPTIONS"]
provide "application/json", :get_json
provide "text/html", :get_html
accept "application/json", :post_json
prepare do
conn.fetch [:cookies, :params]
end
# When collection handlers want to post for new resources...
def allow_missing_post do true end
def service_available
# Some code to determine if we can respond
end
def get_json
get_fruit |> Jiffy.encode |> conn.resp_body
end
def get_html
conn.assign :fruit_collection, get_fruit
render conn, "fruit_collection.html"
end
defp get_fruit
Fruit.to_sequence.reverse
end
def post_json
# some code to write JSON
conn
end
end
defmodule FruitObjectHandler do
use Dynamo.RESTHandler
allowed_methods ["GET", "PUT", "DELETE", "OPTIONS"]
provide "application/json", :get_json
provide "text/html", :get_html
accept "application/json", :put_json
prepare do
conn.fetch [:cookies, :params]
end
def resource_exists
end
def service_available
# Some code to determine if we can respond
end
def last_modified
# The last time this resource was changed
end
def get_json
get_fruit(conn) |> Jiffy.encode |> conn.resp_body
end
def get_html
fruit = get_fruit(conn)
conn.assign(:name, fruit.name)
render(conn, "fruit.html")
end
defp get_fruit(conn)
Fruit.read(conn.params[:fruit_id])
end
def put_json
# some code to write JSON
conn
end
end
defmodule FruitRouter do
use Dynamo
use Dynamo.Router
config :server, port: 3030
# New resource macro for simple restful handlers
resource "/fruit", FruitCollectionHandler
resource "/fruit/:id", FruitObjectHandler
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment