Skip to content

Instantly share code, notes, and snippets.

@richmolj
Created December 2, 2016 17:19
Show Gist options
  • Select an option

  • Save richmolj/bc79619cc30b514f0767a479263b6f06 to your computer and use it in GitHub Desktop.

Select an option

Save richmolj/bc79619cc30b514f0767a479263b6f06 to your computer and use it in GitHub Desktop.
require 'json'
Bundler.require(:default)
require 'sinatra/base'
require 'jsonapi/serializable'
require 'sequel'
require 'pry'
require 'pry-byebug'
DB = Sequel.sqlite(logger: Logger.new($stdout))
DB.extension(:pagination)
DB.create_table :authors do
primary_key :id
String :name
end
DB.create_table :tweets do
primary_key :id
Integer :author_id
String :content
end
class Tweet < Sequel::Model
many_to_one :author
end
class Author < Sequel::Model
one_to_many :tweets
end
Author.insert(name: 'author1')
Author.insert(name: 'author2')
# Populate the table
Tweet.insert(content: 'tweet1', author_id: 1)
Tweet.insert(content: 'tweet2', author_id: 1)
Tweet.insert(content: 'tweet3', author_id: 2)
Renderer = JSONAPI::Serializable::Renderer
class SerializableTweet < JSONAPI::Serializable::Resource
type 'tweets'
attribute :content
belongs_to :author
end
class SerializableAuthor < JSONAPI::Serializable::Resource
type 'authors'
attribute :name
end
class TwitterApp < Sinatra::Application
include JsonapiCompliable
attr_accessor :action_name
def render(opts)
Renderer.render(opts.delete(:jsonapi), opts)
end
jsonapi do
sort do |scope, att, dir|
dir == :desc ? scope.reverse_order(att) : scope.order(att)
end
paginate do |scope, current_page, per_page|
scope.paginate(current_page, per_page, 100) # fake total count to avoid query
end
includes whitelist: { index: :author } do |scope, includes|
scope.eager(includes)
end
end
configure do
mime_type :jsonapi, 'application/vnd.api+json'
end
before do
content_type :jsonapi
end
get '/api/tweets' do
self.action_name = :index
records = jsonapi_scope(Tweet).all
render_jsonapi(records, class: SerializableTweet)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment