Created
June 29, 2013 21:38
-
-
Save aikalima/5892778 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
``` | |
require 'sinatra' | |
require 'sinatra/reloader' | |
require 'json' | |
require 'sqlite3' | |
before do | |
@db = SQLite3::Database.new './store.sqlite3' | |
end | |
get '/products' do | |
rs = @db.execute 'SELECT * FROM products;' | |
return rs.to_json | |
end | |
get '/products/:id' do | |
id = params[:id] | |
rs = @db.execute 'SELECT * FROM products WHERE id = ?;', [id] | |
rs.first.to_json | |
end | |
get '/users' do | |
rs = @db.execute 'SELECT * FROM users;' | |
return rs.to_json | |
end | |
get '/users/:id' do | |
id = params[:id] | |
rs = @db.execute 'SELECT * FROM users WHERE id = ?;', [id] | |
return rs.to_json | |
end | |
get '/wishlists' do | |
rs = @db.execute 'SELECT users.name, products.name FROM products, users, wishlists WHERE products.id = wishlists.product_id AND wishlists.user_id = users.id;' | |
w = reduce_wishlist rs | |
w.to_json | |
end | |
get '/users/:id/wishlist' do | |
id = params[:id] | |
rs = @db.execute 'SELECT users.name, products.name FROM products, users, wishlists WHERE products.id = wishlists.product_id AND wishlists.user_id = users.id AND users.id = ? ;', id | |
w = reduce_wishlist rs | |
w.to_json | |
end | |
private | |
def reduce_wishlist result_set | |
result_set.inject({}) do |all, pair| | |
u = pair[0] | |
p = pair[1] | |
all[u] ||= [] | |
all[u] << p | |
all | |
end | |
end | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment