jsonapi-suite / jsonapi_compliable

MIT License
20 stars 35 forks source link

1.0 rendering #110

Closed richmolj closed 6 years ago

richmolj commented 6 years ago

The immediate developer-facing changes are:

render_jsonapi(Post.all)

 # is now:

render jsonapi: Post.all

And

def show
  scope = jsonapi_scope(Post.where(id: params[:id]))
  render_jsonapi(scope.resolve.first, scope: false)
end

 # is now:

def show
  render jsonapi: Post.where(id: params[:id]), single: true
end

The related effort here is to re-use our rendering code for Resource integration testing. We can now easily run resource queries without a request, controller, or Rails:

require 'active_record'
require 'jsonapi_compliable'

 # ... db configuration ...
class Employee > ActiveRecord::Base
end

class EmployeeResource < JsonapiCompliable::Resource
  type :employees
  model Employee
end

params = { filter: { first_name: 'John' } }
runner = JsonapiCompliable::Runner.new(EmployeeResource.new, params)

json = runner.render_jsonapi(Employee.all)
 # OR
records = runner.records(Employee.all)

 # you can even run in a given context
ctx = OpenStruct.new(current_user: User.new)
JsonapiCompliable.with_context ctx, {} do
  runner.render_jsonapi(Employee.all)
end

This runner is now used in our resource integration test setup (just minor sugar around it):

RSpec.describe 'sorting' do
  include_context 'resource testing'

  let(:resource) { Class.new(EmployeeResource) }
  let(:base_scope) { Employee.all }

  it 'can return records directly' do
    records # => array of model instances
  end

  it 'can return json' do
    render # => json
  end

  it 'works with spec helpers' do
    render
    json_items, json_ids(true), etc
  end
end

Other notes:

richmolj commented 6 years ago

@wadetandy on top of https://github.com/jsonapi-suite/jsonapi_compliable/pull/108

richmolj commented 6 years ago

Can't you default this?

Yes, and we should, just didn't touch it as part of this PR. Have a note of it though.

richmolj commented 6 years ago

One question is why JsonapiCompliable.with_context requires the second {} argument? Can't you default this?

@wadetandy just fyi - now done