Skip to content

Commit

Permalink
Fixes Heroku issues and missing things
Browse files Browse the repository at this point in the history
Added before_all for /todos/:id route
Added options method
Fixed post on /todos to expect order
Added missing header
  • Loading branch information
rzanluchi committed Jul 1, 2016
1 parent 0a7aead commit 416a083
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 7 deletions.
2 changes: 1 addition & 1 deletion shard.yml
@@ -1,4 +1,4 @@
name: todo
name: todo_app
version: 0.1.0

authors:
Expand Down
15 changes: 11 additions & 4 deletions src/todo/handler.cr
Expand Up @@ -5,10 +5,17 @@ module Todo
def initialize(@todo_repo : TodoRepository)
end

def add_todo_item(item_title : String, order : Int32 = nil)
if order == nil
order = @todo_repo.size + 1
end
def add_todo_item(item_title : String, order : Int64)
add_todo_item item_title, order.to_i
end

def add_todo_item(item_title : String, order : Nil)
order = @todo_repo.size + 1
todo_item = TodoItem.new item_title, SecureRandom.uuid, order.as Int32
@todo_repo.save todo_item
end

def add_todo_item(item_title : String, order : Int32)
todo_item = TodoItem.new item_title, SecureRandom.uuid, order.as Int32
@todo_repo.save todo_item
end
Expand Down
27 changes: 25 additions & 2 deletions src/app.cr → src/todo_app.cr
Expand Up @@ -21,6 +21,7 @@ def repr(todo, base_url)
{"uid" => todo._id,
"title" => todo.title,
"order" => todo.order,
"completed" => todo.completed,
"url" => base_url + todo_url(todo._id)
}
end
Expand All @@ -29,20 +30,41 @@ before_all "/todos" do |env|
# Support CORS and set responses to JSON as default.
headers env, {
"Access-Control-Allow-Origin" => "*",
"Content-Type" => "application/json"
"Content-Type" => "application/json",
"Access-Control-Allow-Headers" => "Content-Type"
}
end

before_all "/todos/:id" do |env|
# Support CORS and set responses to JSON as default.
headers env, {
"Access-Control-Allow-Origin" => "*",
"Content-Type" => "application/json",
"Access-Control-Allow-Headers" => "Content-Type"
}
end

get "/" do |env|
env.redirect TODOS_URI
end

options "/todos" do |env|
headers env, {
"Access-Control-Allow-Methods" => "GET,HEAD,POST,DELETE,OPTIONS,PUT,PATCH"
}
end

get "/todos" do |env|
todos = Handler.list_todos
todos.map { |todo| repr(todo, base_url(env)) }.to_json
end

options "/todos/:id" do |env|
headers env, {
"Access-Control-Allow-Methods" => "GET,HEAD,POST,DELETE,OPTIONS,PUT,PATCH"
}
end

get "/todos/:id" do |env|
id = env.params.url["id"].as(String)
todo = Handler.get_todo id
Expand All @@ -51,7 +73,8 @@ end

post "/todos" do |env|
title = env.params.json["title"].as(String)
todo = Handler.add_todo_item title
order = env.params.json.fetch("order", nil) as (Nil | Int64)
todo = Handler.add_todo_item title, order
env.response.status_code = 201
repr(todo, base_url(env)).to_json
end
Expand Down

0 comments on commit 416a083

Please sign in to comment.