diff --git a/lib/librarix/application.rb b/lib/librarix/application.rb index ff2fe7f..cda5fde 100644 --- a/lib/librarix/application.rb +++ b/lib/librarix/application.rb @@ -6,6 +6,7 @@ require 'librarix/helpers' require 'sinatra/base' require 'sinatra/content_for' require 'sinatra/json' +require 'sinatra/namespace' require 'yaml' require 'slim' @@ -24,6 +25,55 @@ module Librarix helpers Librarix::Menu::Helper helpers Librarix::Helpers + namespace '/api/v1' do + helpers do + def base_url + @base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}" + end + + def json_params + begin + JSON.parse(request.body.read) + rescue + halt 400, { message:'Invalid JSON' }.to_json + end + end + end + + before do + content_type 'application/json' + end + + get '/movies' do + Librarix::Filter.new(params).movies.to_json + end + + post '/movies' do + id = json_params['tmdb_id'].to_i + movie = Tmdb::Movie.detail(id) + + if movie['status_code'] != 34 && !Librarix::Redis::Movie.new(id).added? + Librarix::Redis::Movie.new(id).add.to_json + end + end + + get '/movies/:id' do |id| + Librarix::Redis::Movie.new(id).fetch.to_json + end + + get '/movies/:id/fetch' do |id| + Librarix::Redis::Movie.new(id).update + end + + patch '/movies/:id/view' do |id| + Librarix::Redis::Movie.new(params[:id]).view + end + + delete '/movies/:id' do |id| + Librarix::Redis::Movie.new(params[:id]).remove + end + end + get '/' do slim :index, locals: {filter: Librarix::Filter.new(params)} end