From 6d6384a372811a5f3dd6b81154091bb01e4b537f Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Fri, 11 Nov 2016 09:32:43 -0500 Subject: [PATCH 01/60] Bump to 0.9.0.beta1 --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 631ac0c72..3378dd89e 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.9.0.pre' + VERSION = '0.9.0.beta1' end end From bee1551180a1e8b984fd1e699c8b499db6a4bf49 Mon Sep 17 00:00:00 2001 From: Austen Ito Date: Tue, 15 Nov 2016 17:33:38 -0500 Subject: [PATCH 02/60] Fix issue where resources received context nested in hash * If caching has been enabled, however disabled for a resource, the context values are nested in a a 'context' key. For example: { context: { foo: :bar } } vs { foo: :bar } (cherry picked from commit 0936916) --- lib/jsonapi/resource.rb | 2 +- test/controllers/controller_test.rb | 6 ++++++ test/fixtures/active_record.rb | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 14c34d417..af4ded28e 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -1040,7 +1040,7 @@ def cached_resources_for(records, serializer, options) cache_ids = pluck_arel_attributes(records, t[_primary_key], t[_cache_field]) resources = CachedResourceFragment.fetch_fragments(self, serializer, options[:context], cache_ids) else - resources = resources_for(records, options).map{|r| [r.id, r] }.to_h + resources = resources_for(records, options[:context]).map{|r| [r.id, r] }.to_h end preload_included_fragments(resources, records, serializer, options) diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index 83c0bdfac..38baf07c6 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -2451,6 +2451,12 @@ def test_destroy_relationship_has_and_belongs_to_many_refect ensure JSONAPI.configuration.use_relationship_reflection = false end + + def test_index_with_caching_enabled_uses_context + assert_cacheable_get :index + assert_response :success + assert json_response['data'][0]['attributes']['title'] = 'Title' + end end class Api::V5::AuthorsControllerTest < ActionController::TestCase diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 778c72538..469e81f34 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -717,6 +717,9 @@ class BoatsController < JSONAPI::ResourceController end class BooksController < JSONAPI::ResourceController + def context + { title: 'Title' } + end end ### CONTROLLERS @@ -1246,7 +1249,13 @@ class AuthorResource < JSONAPI::Resource end class BookResource < JSONAPI::Resource + attribute :title + has_many :authors, class_name: 'Author', inverse_relationship: :books + + def title + context[:title] + end end class AuthorDetailResource < JSONAPI::Resource From 348d6275dc385617f437f0ace7813eadc1d7e697 Mon Sep 17 00:00:00 2001 From: Hugh Barrigan Date: Mon, 14 Nov 2016 12:52:52 -0500 Subject: [PATCH 03/60] Allow includes to follow namespacing (cherry picked from commit 2f46f58) --- lib/jsonapi/request_parser.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/request_parser.rb b/lib/jsonapi/request_parser.rb index eb0dbf1ee..2929a696a 100644 --- a/lib/jsonapi/request_parser.rb +++ b/lib/jsonapi/request_parser.rb @@ -201,7 +201,7 @@ def check_include(resource_klass, include_parts) relationship = resource_klass._relationship(relationship_name) if relationship && format_key(relationship_name) == include_parts.first unless include_parts.last.empty? - check_include(Resource.resource_for(@resource_klass.module_path + relationship.class_name.to_s.underscore), include_parts.last.partition('.')) + check_include(Resource.resource_for(resource_klass.module_path + relationship.class_name.to_s.underscore), include_parts.last.partition('.')) end else @errors.concat(JSONAPI::Exceptions::InvalidInclude.new(format_key(resource_klass._type), From f92b401f68c68522575860f2566509e85c221068 Mon Sep 17 00:00:00 2001 From: Brandon Blaylock Date: Sat, 12 Nov 2016 12:40:50 -0500 Subject: [PATCH 04/60] Fixed the indentation of meta example in README (cherry picked from commit fd0826a) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 02c6b30cf..ddbfafbb6 100644 --- a/README.md +++ b/README.md @@ -1053,7 +1053,7 @@ class BookResource < JSONAPI::Resource computed_copyright: options[:serialization_options][:copyright], last_updated_at: _model.updated_at } - end + end end ``` From cb3ef23bbc6d4db22128e880c9d90772a25769bc Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Tue, 29 Nov 2016 08:17:30 -0500 Subject: [PATCH 05/60] Update README to use Doc Site --- README.md | 2136 +---------------------------------------------------- 1 file changed, 10 insertions(+), 2126 deletions(-) diff --git a/README.md b/README.md index ddbfafbb6..c494c9c74 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,19 @@ -# JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=master)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources) +# JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=beta)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources) [![Join the chat at https://gitter.im/cerebris/jsonapi-resources](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cerebris/jsonapi-resources?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -**NOTE:** This README is the documentation for `JSONAPI::Resources`. If you are viewing this at the -[project page on Github](https://github.com/cerebris/jsonapi-resources) you are viewing the documentation for the `master` -branch. This may contain information that is not relevant to the release you are using. Please see the README for the -[version](https://github.com/cerebris/jsonapi-resources/releases) you are using. +`JSONAPI::Resources`, or "JR", provides a framework for developing an API server that complies with the +[JSON:API](http://jsonapi.org/) specification. - --- - -`JSONAPI::Resources`, or "JR", provides a framework for developing a server that complies with the -[JSON API](http://jsonapi.org/) specification. - -Like JSON API itself, JR's design is focused on the resources served by an API. JR needs little more than a definition +Like JSON:API itself, JR's design is focused on the resources served by an API. JR needs little more than a definition of your resources, including their attributes and relationships, to make your server compliant with JSON API. -JR is designed to work with Rails 4.0+, and provides custom routes, controllers, and serializers. JR's resources may be +JR is designed to work with Rails 4.2+, and provides custom routes, controllers, and serializers. JR's resources may be backed by ActiveRecord models or by custom objects. -## Table of Contents +## Documentation -* [Demo App] (#demo-app) -* [Client Libraries] (#client-libraries) -* [Installation] (#installation) -* [Usage] (#usage) - * [Resources] (#resources) - * [JSONAPI::Resource] (#jsonapiresource) - * [Context] (#context) - * [Attributes] (#attributes) - * [Primary Key] (#primary-key) - * [Model Name] (#model-name) - * [Model Hints] (#model-hints) - * [Relationships] (#relationships) - * [Filters] (#filters) - * [Pagination] (#pagination) - * [Included relationships (side-loading resources)] (#included-relationships-side-loading-resources) - * [Resource meta] (#resource-meta) - * [Custom Links] (#custom-links) - * [Callbacks] (#callbacks) - * [Controllers] (#controllers) - * [Namespaces] (#namespaces) - * [Error Codes] (#error-codes) - * [Handling Exceptions] (#handling-exceptions) - * [Action Callbacks] (#action-callbacks) - * [Operation Processors] (#operation-processors) - * [Serializer] (#serializer) - * [Serializer options] (#serializer-options) - * [Formatting] (#formatting) - * [Key Format] (#key-format) - * [Routing] (#routing) - * [Nested Routes] (#nested-routes) - * [Authorization](#authorization) - * [Resource Caching] (#resource-caching) - * [Caching Caveats] (#caching-caveats) -* [Configuration] (#configuration) -* [Contributing] (#contributing) -* [License] (#license) +Full documentation can be found at [http://jsonapi-resources.com](http://jsonapi-resources.com), including the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/) specific to this version. ## Demo App @@ -63,8 +21,8 @@ We have a simple demo app, called [Peeps](https://github.com/cerebris/peeps), av ## Client Libraries -JSON API maintains a (non-verified) listing of [client libraries](http://jsonapi.org/implementations/#client-libraries) -which *should* be compatible with JSON API compliant server implementations such as JR. +JSON:API maintains a (non-verified) listing of [client libraries](http://jsonapi.org/implementations/#client-libraries) +which *should* be compatible with JSON:API compliant server implementations such as JR. ## Installation @@ -80,2071 +38,7 @@ Or install it yourself as: $ gem install jsonapi-resources -## Usage - -### Resources - -Resources define the public interface to your API. A resource defines which attributes are exposed, as well as -relationships to other resources. - -Resource definitions should by convention be placed in a directory under app named resources, `app/resources`. The file name should be the single underscored name of the model that backs the resource with `_resource.rb` appended. For example, -a `Contact` model's resource should have a class named `ContactResource` defined in a file named `contact_resource.rb`. - -#### JSONAPI::Resource - -Resources must be derived from `JSONAPI::Resource`, or a class that is itself derived from `JSONAPI::Resource`. - -For example: - -```ruby -class ContactResource < JSONAPI::Resource -end -``` - -A jsonapi-resource generator is available -``` -rails generate jsonapi:resource contact -``` - -##### Abstract Resources - -Resources that are not backed by a model (purely used as base classes for other resources) should be declared as -abstract. - -Because abstract resources do not expect to be backed by a model, they won't attempt to discover the model class -or any of its relationships. - -```ruby -class BaseResource < JSONAPI::Resource - abstract - - has_one :creator -end - -class ContactResource < BaseResource -end -``` - -##### Immutable Resources - -Resources that are immutable should be declared as such with the `immutable` method. Immutable resources will only -generate routes for `index`, `show` and `show_relationship`. - -###### Immutable for Readonly - -Some resources are read-only and are not to be modified through the API. Declaring a resource as immutable prevents -creation of routes that allow modification of the resource. - -###### Immutable Heterogeneous Collections - -Immutable resources can be used as the basis for a heterogeneous collection. Resources in heterogeneous collections can -still be mutated through their own type-specific endpoints. - -```ruby -class VehicleResource < JSONAPI::Resource - immutable - - has_one :owner - attributes :make, :model, :serial_number -end - -class CarResource < VehicleResource - attributes :drive_layout - has_one :driver -end - -class BoatResource < VehicleResource - attributes :length_at_water_line - has_one :captain -end - -# routes - jsonapi_resources :vehicles - jsonapi_resources :cars - jsonapi_resources :boats - -``` - -In the above example vehicles are immutable. A call to `/vehicles` or `/vehicles/1` will return vehicles with types -of either `car` or `boat`. But calls to PUT or POST a `car` must be made to `/cars`. The rails models backing the above -code use Single Table Inheritance. - -#### Context - -Sometimes you will want to access things such as the current logged in user (and other state only available within your controllers) from within your resource classes. To make this state available to a resource class you need to put it into the context hash - this can be done via a `context` method on one of your controllers or across all controllers using ApplicationController. - -For example: - -```ruby -class ApplicationController < JSONAPI::ResourceController - def context - {current_user: current_user} - end -end - -# Specific resource controllers derive from ApplicationController -# and share its context -class PeopleController < ApplicationController - -end - -# Assuming you don't permit user_id (so the client won't assign a wrong user to own the object) -# you can ensure the current user is assigned the record by using the controller's context hash. -class PeopleResource < JSONAPI::Resource - before_save do - @model.user_id = context[:current_user].id if @model.new_record? - end -end -``` - -You can put things that affect serialization and resource configuration into the context. - -#### Attributes - -Any of a resource's attributes that are accessible must be explicitly declared. Single attributes can be declared using -the `attribute` method, and multiple attributes can be declared with the `attributes` method on the resource class. - -For example: - -```ruby -class ContactResource < JSONAPI::Resource - attribute :name_first - attributes :name_last, :email, :twitter -end -``` - -This resource has 4 defined attributes: `name_first`, `name_last`, `email`, `twitter`, as well as the automatically -defined attributes `id` and `type`. By default these attributes must exist on the model that is handled by the resource. - -A resource object wraps a Ruby object, usually an `ActiveModel` record, which is available as the `@model` variable. -This allows a resource's methods to access the underlying model. - -For example, a computed attribute for `full_name` could be defined as such: - -```ruby -class ContactResource < JSONAPI::Resource - attributes :name_first, :name_last, :email, :twitter - attribute :full_name - - def full_name - "#{@model.name_first}, #{@model.name_last}" - end -end -``` - -##### Attribute Delegation - -Normally resource attributes map to an attribute on the model of the same name. Using the `delegate` option allows a resource -attribute to map to a differently named model attribute. For example: - -```ruby -class ContactResource < JSONAPI::Resource - attribute :name_first, delegate: :first_name - attribute :name_last, delegate: :last_name -end -``` - -##### Fetchable Attributes - -By default all attributes are assumed to be fetchable. The list of fetchable attributes can be filtered by overriding -the `fetchable_fields` method. - -Here's an example that prevents guest users from seeing the `email` field: - -```ruby -class AuthorResource < JSONAPI::Resource - attributes :name, :email - model_name 'Person' - has_many :posts - - def fetchable_fields - if (context[:current_user].guest) - super - [:email] - else - super - end - end -end -``` - -Context flows through from the controller to the resource and can be used to control the attributes based on the -current user (or other value). - -##### Creatable and Updatable Attributes - -By default all attributes are assumed to be updatable and creatable. To prevent some attributes from being accepted by -the `update` or `create` methods, override the `self.updatable_fields` and `self.creatable_fields` methods on a resource. - -This example prevents `full_name` from being set: - -```ruby -class ContactResource < JSONAPI::Resource - attributes :name_first, :name_last, :full_name - - def full_name - "#{@model.name_first}, #{@model.name_last}" - end - - def self.updatable_fields(context) - super - [:full_name] - end - - def self.creatable_fields(context) - super - [:full_name] - end -end -``` - -The `context` is not by default used by the `ResourceController`, but may be used if you override the controller methods. -By using the context you have the option to determine the creatable and updatable fields based on the user. - -##### Sortable Attributes - -JR supports [sorting primary resources by multiple sort criteria](http://jsonapi.org/format/#fetching-sorting). - -By default all attributes are assumed to be sortable. To prevent some attributes from being sortable, override the -`self.sortable_fields` method on a resource. - -Here's an example that prevents sorting by post's `body`: - -```ruby -class PostResource < JSONAPI::Resource - attributes :title, :body - - def self.sortable_fields(context) - super(context) - [:body] - end -end -``` - -JR also supports sorting primary resources by fields on relationships. - -Here's an example of sorting books by the author name: - -```ruby -class Book < ActiveRecord::Base - belongs_to :author -end - -class Author < ActiveRecord::Base - has_many :books -end - -class BookResource < JSONAPI::Resource - attributes :title, :body - - def self.sortable_fields(context) - super(context) << :"author.name" - end -end -``` -The request will look something like: -``` -GET /books?include=author&sort=author.name -``` - -###### Default sorting - -By default JR sorts ascending on the `id` of the primary resource, unless the request specifies an alternate sort order. -To override this you may override the `self.default_sort` on a `resource`. `default_sort` should return an array of -`sort_param` hashes. A `sort_param` hash contains a `field` and a `direction`, with `direction` being either `:asc` or -`:desc`. - -For example: - -```ruby - def self.default_sort - [{field: 'name_last', direction: :desc}, {field: 'name_first', direction: :desc}] - end -``` - -##### Attribute Formatting - -Attributes can have a `Format`. By default all attributes use the default formatter. If an attribute has the `format` -option set the system will attempt to find a formatter based on this name. In the following example the `last_login_time` -will be returned formatted to a certain time zone: - -```ruby -class PersonResource < JSONAPI::Resource - attributes :name, :email - attribute :last_login_time, format: :date_with_timezone -end -``` - -The system will lookup a value formatter named `DateWithTimezoneValueFormatter` and will use this when serializing and -updating the attribute. See the [Value Formatters](#value-formatters) section for more details. - -##### Flattening a Rails relationship - -It is possible to flatten Rails relationships into attributes by using getters and setters. This can become handy if a relation needs to be created alongside the creation of the main object which can be the case if there is a bi-directional presence validation. For example: - -```ruby -# Given Models -class Person < ActiveRecord::Base - has_many :spoken_languages - validates :name, :email, :spoken_languages, presence: true -end - -class SpokenLanguage < ActiveRecord::Base - belongs_to :person, inverse_of: :spoken_languages - validates :person, :language_code, presence: true -end - -# Resource with getters and setter -class PersonResource < JSONAPI::Resource - attributes :name, :email, :spoken_languages - - # Getter - def spoken_languages - @model.spoken_languages.pluck(:language_code) - end - - # Setter (because spoken_languages needed for creation) - def spoken_languages=(new_spoken_language_codes) - @model.spoken_languages.destroy_all - new_spoken_language_codes.each do |new_lang_code| - @model.spoken_languages.build(language_code: new_lang_code) - end - end -end -``` - -#### Primary Key - -Resources are always represented using a key of `id`. The resource will interrogate the model to find the primary key. -If the underlying model does not use `id` as the primary key _and_ does not support the `primary_key` method you -must use the `primary_key` method to tell the resource which field on the model to use as the primary key. **Note:** -this _must_ be the actual primary key of the model. - -By default only integer values are allowed for primary key. To change this behavior you can set the `resource_key_type` -configuration option: - -```ruby -JSONAPI.configure do |config| - # Allowed values are :integer(default), :uuid, :string, or a proc - config.resource_key_type = :uuid -end -``` - -##### Override key type on a resource - -You can override the default resource key type on a per-resource basis by calling `key_type` in the resource class, -with the same allowed values as the `resource_key_type` configuration option. - -```ruby -class ContactResource < JSONAPI::Resource - attribute :id - attributes :name_first, :name_last, :email, :twitter - key_type :uuid -end -``` - -##### Custom resource key validators - -If you need more control over the key, you can override the #verify_key method on your resource, or set a lambda that -accepts key and context arguments in `config/initializers/jsonapi_resources.rb`: - -```ruby -JSONAPI.configure do |config| - config.resource_key_type = -> (key, context) { key && String(key) } -end -``` - -#### Model Name - -The name of the underlying model is inferred from the Resource name. It can be overridden by use of the `model_name` -method. For example: - -```ruby -class AuthorResource < JSONAPI::Resource - attribute :name - model_name 'Person' - has_many :posts -end -``` - -#### Model Hints - -Resource instances are created from model records. The determination of the correct resource type is performed using a -simple rule based on the model's name. The name is used to find a resource in the same module (as the originating -resource) that matches the name. This usually works quite well, however it can fail when model names do not match -resource names. It can also fail when using namespaced models. In this case a `model_hint` can be created to map model -names to resources. For example: - -```ruby -class AuthorResource < JSONAPI::Resource - attribute :name - model_name 'Person' - model_hint model: Commenter, resource: :special_person - - has_many :posts - has_many :commenters -end -``` - -Note that when `model_name` is set a corresponding `model_hint` is also added. This can be skipped by using the -`add_model_hint` option set to false. For example: - -```ruby -class AuthorResource < JSONAPI::Resource - model_name 'Legacy::Person', add_model_hint: false -end -``` - -Model hints inherit from parent resources, but are not global in scope. The `model_hint` method accepts `model` and -`resource` named parameters. `model` takes an ActiveRecord class or class name (defaults to the model name), and -`resource` takes a resource type or a resource class (defaults to the current resource's type). - -#### Relationships - -Related resources need to be specified in the resource. These may be declared with the `relationship` or the `has_one` -and the `has_many` methods. - -Here's a simple example using the `relationship` method where a post has a single author and an author can have many -posts: - -```ruby -class PostResource < JSONAPI::Resource - attributes :title, :body - - relationship :author, to: :one -end -``` - -And the corresponding author: - -```ruby -class AuthorResource < JSONAPI::Resource - attribute :name - - relationship :posts, to: :many -end -``` - -And here's the equivalent resources using the `has_one` and `has_many` methods: - -```ruby -class PostResource < JSONAPI::Resource - attributes :title, :body - - has_one :author -end -``` - -And the corresponding author: - -```ruby -class AuthorResource < JSONAPI::Resource - attribute :name - - has_many :posts -end -``` - -##### Options - -The relationship methods (`relationship`, `has_one`, and `has_many`) support the following options: - - * `class_name` - a string specifying the underlying class for the related resource. Defaults to the `class_name` property on the underlying model. - * `foreign_key` - the method on the resource used to fetch the related resource. Defaults to `_id` for has_one and `_ids` for has_many relationships. - * `acts_as_set` - allows the entire set of related records to be replaced in one operation. Defaults to false if not set. - * `polymorphic` - set to true to identify relationships that are polymorphic. - * `relation_name` - the name of the relation to use on the model. A lambda may be provided which allows conditional selection of the relation based on the context. - * `always_include_linkage_data` - if set to true, the relationship includes linkage data. Defaults to false if not set. - * `eager_load_on_include` - if set to false, will not include this relationship in join SQL when requested via an include. You usually want to leave this on, but it will break 'relationships' which are not active record, for example if you want to expose a tree using the `ancestry` gem or similar, or the SQL query becomes too large to handle. Defaults to true if not set. - -`to_one` relationships support the additional option: - * `foreign_key_on` - defaults to `:self`. To indicate that the foreign key is on the related resource specify `:related`. - -`to_many` relationships support the additional option: - * `reflect` - defaults to `true`. To indicate that updates to the relationship are performed on the related resource, if relationship reflection is turned on. See [Configuration] (#configuration) - -Examples: - -```ruby -class CommentResource < JSONAPI::Resource - attributes :body - has_one :post - has_one :author, class_name: 'Person' - has_many :tags, acts_as_set: true -end - -class ExpenseEntryResource < JSONAPI::Resource - attributes :cost, :transaction_date - - has_one :currency, class_name: 'Currency', foreign_key: 'currency_code' - has_one :employee -end - -class TagResource < JSONAPI::Resource - attributes :name - has_one :taggable, polymorphic: true -end -``` - -```ruby -class BookResource < JSONAPI::Resource - - # Only book_admins may see unapproved comments for a book. Using - # a lambda to select the correct relation on the model - has_many :book_comments, relation_name: -> (options = {}) { - context = options[:context] - current_user = context ? context[:current_user] : nil - - unless current_user && current_user.book_admin - :approved_book_comments - else - :book_comments - end - } - ... -end -``` - -The polymorphic relationship will require the resource and controller to exist, although routing to them will cause an -error. - -```ruby -class TaggableResource < JSONAPI::Resource; end -class TaggablesController < JSONAPI::ResourceController; end -``` - -#### Filters - -Filters for locating objects of the resource type are specified in the resource definition. Single filters can be -declared using the `filter` method, and multiple filters can be declared with the `filters` method on the resource -class. - -For example: - -```ruby -class ContactResource < JSONAPI::Resource - attributes :name_first, :name_last, :email, :twitter - - filter :id - filters :name_first, :name_last -end -``` - -Then a request could pass in a filter for example `http://example.com/contacts?filter[name_last]=Smith` and the system -will find all people where the last name exactly matches Smith. - -##### Default Filters - -A default filter may be defined for a resource using the `default` option on the `filter` method. This default is used -unless the request overrides this value. - -For example: - -```ruby - class CommentResource < JSONAPI::Resource - attributes :body, :status - has_one :post - has_one :author - - filter :status, default: 'published,pending' -end -``` - -The default value is used as if it came from the request. - -##### Applying Filters - -You may customize how a filter behaves by supplying a callable to the `:apply` option. This callable will be used to -apply that filter. The callable is passed the `records`, which is an `ActiveRecord::Relation`, the `value`, and an -`_options` hash. It is expected to return an `ActiveRecord::Relation`. - -Note: When a filter is not supplied a `verify` callable to modify the `value` that the `apply` callable receives, -`value` defaults to an array of the string values provided to the filter parameter. - -This example shows how you can implement different approaches for different filters. - -```ruby -# When given the following parameter:'filter[visibility]': 'public' - -filter :visibility, apply: ->(records, value, _options) { - records.where('users.publicly_visible = ?', value[0] == 'public') -} -``` - -If you omit the `apply` callable the filter will be applied as `records.where(filter => value)`. - -Note: It is also possible to override the `self.apply_filter` method, though this approach is now deprecated: - -```ruby -def self.apply_filter(records, filter, value, options) - case filter - when :last_name, :first_name, :name - if value.is_a?(Array) - value.each do |val| - records = records.where(_model_class.arel_table[filter].matches(val)) - end - records - else - records.where(_model_class.arel_table[filter].matches(value)) - end - else - super(records, filter, value) - end -end -``` - -##### Verifying Filters - -Because filters typically come straight from the request, it's prudent to verify their values. To do so, provide a -callable to the `verify` option. This callable will be passed the `value` and the `context`. Verify should return the -verified value, which may be modified. - -```ruby - filter :ids, - verify: ->(values, context) { - verify_keys(values, context) - values - }, - apply: ->(records, value, _options) { - records.where('id IN (?)', value) - } -``` - -```ruby -# A more complex example, showing how to filter for any overlap between the -# value array and the possible_ids, using both verify and apply callables. - - filter :possible_ids, - verify: ->(values, context) { - values.map {|value| value.to_i} - }, - apply: ->(records, value, _options) { - records.where('possible_ids && ARRAY[?]', value) - } -``` - -##### Finders - -Basic finding by filters is supported by resources. This is implemented in the `find` and `find_by_key` finder methods. -Currently this is implemented for `ActiveRecord` based resources. The finder methods rely on the `records` method to get -an `ActiveRecord::Relation` relation. It is therefore possible to override `records` to affect the three find related -methods. - -###### Customizing base records for finder methods - -If you need to change the base records on which `find` and `find_by_key` operate, you can override the `records` method -on the resource class. - -For example to allow a user to only retrieve his own posts you can do the following: - -```ruby -class PostResource < JSONAPI::Resource - attributes :title, :body - - def self.records(options = {}) - context = options[:context] - context[:current_user].posts - end -end -``` - -When you create a relationship, a method is created to fetch record(s) for that relationship, using the relation name -for the relationship. - -```ruby -class PostResource < JSONAPI::Resource - has_one :author - has_many :comments - - # def record_for_author - # relationship = self.class._relationship(:author) - # relation_name = relationship.relation_name(context: @context) - # records_for(relation_name) - # end - - # def records_for_comments - # relationship = self.class._relationship(:comments) - # relation_name = relationship.relation_name(context: @context) - # records_for(relation_name) - # end -end - -``` - -For example, you may want to raise an error if the user is not authorized to view the related records. See the next -section for additional details on raising errors. - -```ruby -class BaseResource < JSONAPI::Resource - def records_for(relation_name) - context = options[:context] - records = _model.public_send(relation_name) - - unless context[:current_user].can_view?(records) - raise NotAuthorizedError - end - - records - end -end -``` - -###### Raising Errors - -Inside the finder methods (like `records_for`) or inside of resource callbacks -(like `before_save`) you can `raise` an error to halt processing. JSONAPI::Resources -has some built in errors that will return appropriate error codes. By -default any other error that you raise will return a `500` status code -for a general internal server error. - -To return useful error codes that represent application errors you -should set the `exception_class_whitelist` config variable, and then you -should use the Rails `rescue_from` macro to render a status code. - -For example, this config setting allows the `NotAuthorizedError` to bubble up out of -JSONAPI::Resources and into your application. - -```ruby -# config/initializer/jsonapi-resources.rb -JSONAPI.configure do |config| - config.exception_class_whitelist = [NotAuthorizedError] -end -``` - -Handling the error and rendering the appropriate code is now the responsibility of the -application and could be handled like this: - -```ruby -class ApiController < ApplicationController - rescue_from NotAuthorizedError, with: :reject_forbidden_request - def reject_forbidden_request - render json: {error: 'Forbidden'}, :status => 403 - end -end -``` - - -###### Applying Filters - -The `apply_filter` method is called to apply each filter to the `Arel` relation. You may override this method to gain -control over how the filters are applied to the `Arel` relation. - -This example shows how you can implement different approaches for different filters. - -```ruby -def self.apply_filter(records, filter, value, options) - case filter - when :visibility - records.where('users.publicly_visible = ?', value == :public) - when :last_name, :first_name, :name - if value.is_a?(Array) - value.each do |val| - records = records.where(_model_class.arel_table[filter].matches(val)) - end - records - else - records.where(_model_class.arel_table[filter].matches(value)) - end - else - super(records, filter, value) - end -end -``` - - -###### Applying Sorting - -You can override the `apply_sort` method to gain control over how the sorting is done. This may be useful in case you'd -like to base the sorting on variables in your context. - -Example: - -```ruby -def self.apply_sort(records, order_options, context = {}) - if order_options.has?(:trending) - records = records.order_by_trending_scope - order_options - [:trending] - end - - super(records, order_options, context) -end -``` - - -###### Override finder methods - -Finally if you have more complex requirements for finding you can override the `find` and `find_by_key` methods on the -resource class. - -Here's an example that defers the `find` operation to a `current_user` set on the `context` option: - -```ruby -class AuthorResource < JSONAPI::Resource - attribute :name - model_name 'Person' - has_many :posts - - filter :name - - def self.find(filters, options = {}) - context = options[:context] - authors = context[:current_user].find_authors(filters) - - return authors.map do |author| - self.new(author, context) - end - end -end -``` - -#### Pagination - -Pagination is performed using a `paginator`, which is a class responsible for parsing the `page` request parameters and -applying the pagination logic to the results. - -##### Paginators - -`JSONAPI::Resource` supports several pagination methods by default, and allows you to implement a custom system if the -defaults do not meet your needs. - -###### Paged Paginator - -The `paged` `paginator` returns results based on pages of a fixed size. Valid `page` parameters are `number` and `size`. -If `number` is omitted the first page is returned. If `size` is omitted the `default_page_size` from the configuration -settings is used. - -``` -GET /articles?page%5Bnumber%5D=10&page%5Bsize%5D=10 HTTP/1.1 -Accept: application/vnd.api+json -``` - -###### Offset Paginator - -The `offset` `paginator` returns results based on an offset from the beginning of the resultset. Valid `page` parameters -are `offset` and `limit`. If `offset` is omitted a value of 0 will be used. If `limit` is omitted the `default_page_size` -from the configuration settings is used. - -``` -GET /articles?page%5Blimit%5D=10&page%5Boffset%5D=10 HTTP/1.1 -Accept: application/vnd.api+json -``` - -###### Custom Paginators - -Custom `paginators` can be used. These should derive from `Paginator`. The `apply` method takes a `relation` and -`order_options` and is expected to return a `relation`. The `initialize` method receives the parameters from the `page` -request parameters. It is up to the paginator author to parse and validate these parameters. - -For example, here is a very simple single record at a time paginator: - -```ruby -class SingleRecordPaginator < JSONAPI::Paginator - def initialize(params) - # param parsing and validation here - @page = params.to_i - end - - def apply(relation, order_options) - relation.offset(@page).limit(1) - end -end -``` - -##### Paginator Configuration - -The default paginator, which will be used for all resources, is set using `JSONAPI.configure`. For example, in your -`config/initializers/jsonapi_resources.rb`: - -```ruby -JSONAPI.configure do |config| - # built in paginators are :none, :offset, :paged - config.default_paginator = :offset - - config.default_page_size = 10 - config.maximum_page_size = 20 -end -``` - -If no `default_paginator` is configured, pagination will be disabled by default. - -Paginators can also be set at the resource-level, which will override the default setting. This is done using the -`paginator` method: - -```ruby -class BookResource < JSONAPI::Resource - attribute :title - attribute :isbn - - paginator :offset -end -``` - -To disable pagination in a resource, specify `:none` for `paginator`. - -#### Included relationships (side-loading resources) - -JR supports [request include params](http://jsonapi.org/format/#fetching-includes) out of the box, for side loading related resources. - -Here's an example from the spec: - -``` -GET /articles/1?include=comments HTTP/1.1 -Accept: application/vnd.api+json -``` - -Will get you the following payload by default: - -``` -{ - "data": { - "type": "articles", - "id": "1", - "attributes": { - "title": "JSON API paints my bikeshed!" - }, - "links": { - "self": "http://example.com/articles/1" - }, - "relationships": { - "comments": { - "links": { - "self": "http://example.com/articles/1/relationships/comments", - "related": "http://example.com/articles/1/comments" - }, - "data": [ - { "type": "comments", "id": "5" }, - { "type": "comments", "id": "12" } - ] - } - } - }, - "included": [{ - "type": "comments", - "id": "5", - "attributes": { - "body": "First!" - }, - "links": { - "self": "http://example.com/comments/5" - } - }, { - "type": "comments", - "id": "12", - "attributes": { - "body": "I like XML better" - }, - "links": { - "self": "http://example.com/comments/12" - } - }] -} -``` - -Note: When passing `include` and `fields` params together, relationships not included in the `fields` parameter will not be serialized. This will have the side effect of not serializing the included resources. To ensure the related resources are properly side loaded specify them in the `fields`, like `fields[posts]=comments,title&include=comments`. - -#### Resource Meta - -Meta information can be included for each resource using the meta method in the resource declaration. For example: - -```ruby -class BookResource < JSONAPI::Resource - attribute :title - attribute :isbn - - def meta(options) - { - copyright: 'API Copyright 2015 - XYZ Corp.', - computed_copyright: options[:serialization_options][:copyright], - last_updated_at: _model.updated_at - } - end -end - -``` - -The `meta` method will be called for each resource instance. Override the `meta` method on a resource class to control -the meta information for the resource. If a non empty hash is returned from `meta` this will be serialized. The `meta` -method is called with an `options` hash. The `options` hash will contain the following: - - * `:serializer` -> the serializer instance - * `:serialization_options` -> the contents of the `serialization_options` method on the controller. - -#### Custom Links - -Custom links can be included for each resource by overriding the `custom_links` method. If a non empty hash is returned from `custom_links`, it will be merged with the default links hash containing the resource's `self` link. The `custom_links` method is called with the same `options` hash used by for [resource meta information](#resource-meta). The `options` hash contains the following: - - * `:serializer` -> the serializer instance - * `:serialization_options` -> the contents of the `serialization_options` method on the controller. - -For example: - -```ruby -class CityCouncilMeeting < JSONAPI::Resource - attribute :title, :location, :approved - - def custom_links(options) - { minutes: options[:serializer].link_builder.self_link(self) + "/minutes" } - end -end -``` - -This will create a custom link with the key `minutes`, which will be merged with the default `self` link, like so: - -```json -{ - "data": [ - { - "id": "1", - "type": "cityCouncilMeetings", - "links": { - "self": "http://city.gov/api/city-council-meetings/1", - "minutes": "http://city.gov/api/city-council-meetings/1/minutes" - }, - "attributes": {...} - }, - //... - ] -} -``` - -Of course, the `custom_links` method can include logic to include links only when relevant: - -````ruby -class CityCouncilMeeting < JSONAPI::Resource - attribute :title, :location, :approved - - delegate :approved?, to: :model - - def custom_links(options) - extra_links = {} - if approved? - extra_links[:minutes] = options[:serializer].link_builder.self_link(self) + "/minutes" - end - extra_links - end -end -``` - -It's also possibly to suppress the default `self` link by returning a hash with `{self: nil}`: - -````ruby -class Selfless < JSONAPI::Resource - def custom_links(options) - {self: nil} - end -end -``` - -#### Callbacks - -`ActiveSupport::Callbacks` is used to provide callback functionality, so the behavior is very similar to what you may be -used to from `ActiveRecord`. - -For example, you might use a callback to perform authorization on your resource before an action. - -```ruby -class BaseResource < JSONAPI::Resource - before_create :authorize_create - - def authorize_create - # ... - end -end -``` - -The types of supported callbacks are: -- `before` -- `after` -- `around` - -##### `JSONAPI::Resource` Callbacks - -Callbacks can be defined for the following `JSONAPI::Resource` events: - -- `:create` -- `:update` -- `:remove` -- `:save` -- `:create_to_many_link` -- `:replace_to_many_links` -- `:create_to_one_link` -- `:replace_to_one_link` -- `:remove_to_many_link` -- `:remove_to_one_link` -- `:replace_fields` - -###### Relationship Reflection - -By default updates to relationships only invoke callbacks on the primary -Resource. By setting the `use_relationship_reflection` [Configuration] (#configuration) option -updates to `has_many` relationships will occur on the related resource, triggering -callbacks on both resources. - -##### `JSONAPI::Processor` Callbacks - -Callbacks can also be defined for `JSONAPI::Processor` events: -- `:operation`: Any individual operation. -- `:find`: A `find` operation is being processed. -- `:show`: A `show` operation is being processed. -- `:show_relationship`: A `show_relationship` operation is being processed. -- `:show_related_resource`: A `show_related_resource` operation is being processed. -- `:show_related_resources`: A `show_related_resources` operation is being processed. -- `:create_resource`: A `create_resource` operation is being processed. -- `:remove_resource`: A `remove_resource` operation is being processed. -- `:replace_fields`: A `replace_fields` operation is being processed. -- `:replace_to_one_relationship`: A `replace_to_one_relationship` operation is being processed. -- `:create_to_many_relationship`: A `create_to_many_relationship` operation is being processed. -- `:replace_to_many_relationship`: A `replace_to_many_relationship` operation is being processed. -- `:remove_to_many_relationship`: A `remove_to_many_relationship` operation is being processed. -- `:remove_to_one_relationship`: A `remove_to_one_relationship` operation is being processed. - -See [Operation Processors] (#operation-processors) for details on using OperationProcessors - -##### `JSONAPI::OperationsProcessor` Callbacks (a removed feature) - -Note: The `JSONAPI::OperationsProcessor` has been removed and replaced with the `JSONAPI::OperationDispatcher` -and `Processor` classes per resource. The callbacks have been renamed and moved to the -`Processor`s, with the exception of the `operations` callback which is now on the controller. - -### Controllers - -There are two ways to implement a controller for your resources. Either derive from `ResourceController` or import -the `ActsAsResourceController` module. - -##### ResourceController - -`JSONAPI::Resources` provides a class, `ResourceController`, that can be used as the base class for your controllers. -`ResourceController` supports `index`, `show`, `create`, `update`, and `destroy` methods. Just deriving your controller -from `ResourceController` will give you a fully functional controller. - -For example: - -```ruby -class PeopleController < JSONAPI::ResourceController - -end -``` - -Of course you are free to extend this as needed and override action handlers or other methods. - -A jsonapi-controller generator is avaliable - -``` -rails generate jsonapi:controller contact -``` - -###### ResourceControllerMetal - -`JSONAPI::Resources` also provides an alternative class to `ResourceController` called `ResourceControllerMetal`. -In order to provide a lighter weight controller option this strips the controller down to just the classes needed -to work with `JSONAPI::Resources`. - -For example: - -```ruby -class PeopleController < JSONAPI::ResourceControllerMetal - -end -``` - -Note: This may not provide all of the expected controller capabilities if you are using additional gems such as DoorKeeper. - -###### Serialization Options - -Additional options can be passed to the serializer using the `serialization_options` method. - -For example: - -```ruby -class ApplicationController < JSONAPI::ResourceController - def serialization_options - {copyright: 'Copyright 2015'} - end -end -``` - -These `serialization_options` are passed to the `meta` method used to generate resource `meta` values. - -##### ActsAsResourceController - -`JSONAPI::Resources` also provides a module, `JSONAPI::ActsAsResourceController`. You can include this module to -mix in all the features of `ResourceController` into your existing controller class. - -For example: - -```ruby -class PostsController < ActionController::Base - include JSONAPI::ActsAsResourceController -end -``` - -#### Namespaces - -JSONAPI::Resources supports namespacing of controllers and resources. With namespacing you can version your API. - -If you namespace your controller it will require a namespaced resource. - -In the following example we have a `resource` that isn't namespaced, and one that has now been namespaced. There are -slight differences between the two resources, as might be seen in a new version of an API: - -```ruby -class PostResource < JSONAPI::Resource - attribute :title - attribute :body - attribute :subject - - has_one :author, class_name: 'Person' - has_one :section - has_many :tags, acts_as_set: true - has_many :comments, acts_as_set: false - def subject - @model.title - end - - filters :title, :author, :tags, :comments - filter :id -end - -... - -module Api - module V1 - class PostResource < JSONAPI::Resource - # V1 replaces the non-namespaced resource - # V1 no longer supports tags and now calls author 'writer' - attribute :title - attribute :body - attribute :subject - - has_one :writer, foreign_key: 'author_id' - has_one :section - has_many :comments, acts_as_set: false - - def subject - @model.title - end - - filters :writer - end - - class WriterResource < JSONAPI::Resource - attributes :name, :email - model_name 'Person' - has_many :posts - - filter :name - end - end -end -``` - -The following controllers are used: - -```ruby -class PostsController < JSONAPI::ResourceController -end - -module Api - module V1 - class PostsController < JSONAPI::ResourceController - end - end -end -``` - -You will also need to namespace your routes: - -```ruby -Rails.application.routes.draw do - - jsonapi_resources :posts - - namespace :api do - namespace :v1 do - jsonapi_resources :posts - end - end -end -``` - -When a namespaced `resource` is used, any related `resources` must also be in the same namespace. - -#### Error codes - -Error codes are provided for each error object returned, based on the error. These errors are: - -```ruby -module JSONAPI - VALIDATION_ERROR = '100' - INVALID_RESOURCE = '101' - FILTER_NOT_ALLOWED = '102' - INVALID_FIELD_VALUE = '103' - INVALID_FIELD = '104' - PARAM_NOT_ALLOWED = '105' - PARAM_MISSING = '106' - INVALID_FILTER_VALUE = '107' - COUNT_MISMATCH = '108' - KEY_ORDER_MISMATCH = '109' - KEY_NOT_INCLUDED_IN_URL = '110' - INVALID_INCLUDE = '112' - RELATION_EXISTS = '113' - INVALID_SORT_CRITERIA = '114' - INVALID_LINKS_OBJECT = '115' - TYPE_MISMATCH = '116' - INVALID_PAGE_OBJECT = '117' - INVALID_PAGE_VALUE = '118' - INVALID_FIELD_FORMAT = '119' - INVALID_FILTERS_SYNTAX = '120' - SAVE_FAILED = '121' - FORBIDDEN = '403' - RECORD_NOT_FOUND = '404' - NOT_ACCEPTABLE = '406' - UNSUPPORTED_MEDIA_TYPE = '415' - LOCKED = '423' -end -``` - -These codes can be customized in your app by creating an initializer to override any or all of the codes. - -In addition textual error codes can be returned by setting the configuration option `use_text_errors = true`. For -example: - -```ruby -JSONAPI.configure do |config| - config.use_text_errors = true -end -``` - - -#### Handling Exceptions - -By default, all exceptions raised downstream from a resource controller will be caught, logged, and a ```500 Internal Server Error``` will be rendered. Exceptions can be whitelisted in the config to pass through the handler and be caught manually, or you can pass a callback from a resource controller to insert logic into the rescue block without interrupting the control flow. This can be particularly useful for additional logging or monitoring without the added work of rendering responses. - -Pass a block, refer to controller class methods, or both. Note that methods must be defined as class methods on a controller and accept one parameter, which is passed the exception object that was rescued. - -```ruby - class ApplicationController < JSONAPI::ResourceController - - on_server_error :first_callback - - #or - - # on_server_error do |error| - #do things - #end - - def self.first_callback(error) - #env["airbrake.error_id"] = notify_airbrake(error) - end - end - -``` - -#### Action Callbacks - -##### verify_content_type_header - -By default, when controllers extend functionalities from `jsonapi-resources`, the `ActsAsResourceController#verify_content_type_header` -method will be triggered before `create`, `update`, `create_relationship` and `update_relationship` actions. This method is responsible -for checking if client's request corresponds to the correct media type required by [JSON API](http://jsonapi.org/format/#content-negotiation-clients): `application/vnd.api+json`. - -In case you need to check the media type for custom actions, just make sure to call the method in your controller's `before_action`: - -```ruby -class UsersController < JSONAPI::ResourceController - before_action :verify_content_type_header, only: [:auth] - - def auth - # some crazy auth code goes here - end -end -``` - -### Operation Processors - -Operation Processors are called to perform the operation(s) that make up a request. The controller (through the `OperationDispatcher`), creates an `OperatorProcessor` to handle each operation. The processor is created based on the resource name, including the namespace. If a processor does not exist for a resource (namespace matters) the default operation processor is used instead. The default processor can be changed by a configuration setting. - -Defining a custom `Processor` allows for custom callback handling of each operation type for each resource type. For example: - -```ruby -class Api::V4::BookProcessor < JSONAPI::Processor - after_find do - unless @result.is_a?(JSONAPI::ErrorsOperationResult) - @result.meta[:total_records_found] = @result.record_count - end - end -end -``` - -This simple example uses a callback to update the result's meta property with the total count of records (a redundant -feature only for example purposes), if there wasn't an error in the operation. It is also possible to override the -`find` method as well if a different behavior is needed, for example: - -```ruby -class Api::V4::BookProcessor < JSONAPI::Processor - def find - filters = params[:filters] - include_directives = params[:include_directives] - sort_criteria = params.fetch(:sort_criteria, []) - paginator = params[:paginator] - - verified_filters = resource_klass.verify_filters(filters, context) - resource_records = resource_klass.find(verified_filters, - context: context, - include_directives: include_directives, - sort_criteria: sort_criteria, - paginator: paginator) - - page_options = {} - # Overriding the default record count logic to always include it in the meta - #if (JSONAPI.configuration.top_level_meta_include_record_count || - # (paginator && paginator.class.requires_record_count)) - page_options[:record_count] = resource_klass.find_count(verified_filters, - context: context, - include_directives: include_directives) - #end -end -``` - -Note: The authors of this gem expect the most common uses cases to be handled using the callbacks. It is likely that the -internal functionality of the operation processing methods will change, at least for several revisions. Effort will be -made to call this out in release notes. You have been warned. - -### Serializer - -The `ResourceSerializer` can be used to serialize a resource into JSON API compliant JSON. `ResourceSerializer` must be - initialized with the primary resource type it will be serializing. `ResourceSerializer` has a `serialize_to_hash` - method that takes a resource instance or array of resource instances to serialize. For example: - -```ruby -post = Post.find(1) -JSONAPI::ResourceSerializer.new(PostResource).serialize_to_hash(PostResource.new(post, nil)) -``` - -Note: If your resource needs to access to state from a context hash, make sure to pass the context hash as the second argument of -the resource class new method. For example: - -```ruby -post = Post.find(1) -context = { current_user: current_user } -JSONAPI::ResourceSerializer.new(PostResource).serialize_to_hash(PostResource.new(post, context)) -``` - -This returns results like this: - -```json -{ - "data": { - "type": "posts", - "id": "1", - "links": { - "self": "http://example.com/posts/1" - }, - "attributes": { - "title": "New post", - "body": "A body!!!", - "subject": "New post" - }, - "relationships": { - "section": { - "links": { - "self": "http://example.com/posts/1/relationships/section", - "related": "http://example.com/posts/1/section" - }, - "data": null - }, - "author": { - "links": { - "self": "http://example.com/posts/1/relationships/author", - "related": "http://example.com/posts/1/author" - }, - "data": { - "type": "people", - "id": "1" - } - }, - "tags": { - "links": { - "self": "http://example.com/posts/1/relationships/tags", - "related": "http://example.com/posts/1/tags" - } - }, - "comments": { - "links": { - "self": "http://example.com/posts/1/relationships/comments", - "related": "http://example.com/posts/1/comments" - } - } - } - } -} -``` - -#### Serializer options - -The `ResourceSerializer` can be initialized with some optional parameters: - -##### `include` - -An array of resources. Nested resources can be specified with dot notation. - - *Purpose*: determines which objects will be side loaded with the source objects in an `included` section - - *Example*: ```include: ['comments','author','comments.tags','author.posts']``` - -##### `fields` - -A hash of resource types and arrays of fields for each resource type. - - *Purpose*: determines which fields are serialized for a resource type. This encompasses both attributes and - relationship ids in the links section for a resource. Fields are global for a resource type. - - *Example*: ```fields: { people: [:email, :comments], posts: [:title, :author], comments: [:body, :post]}``` - -```ruby -post = Post.find(1) -include_resources = ['comments','author','comments.tags','author.posts'] - -JSONAPI::ResourceSerializer.new(PostResource, include: include_resources, - fields: { - people: [:email, :comments], - posts: [:title, :author], - tags: [:name], - comments: [:body, :post] - } -).serialize_to_hash(PostResource.new(post, nil)) -``` - -#### Formatting - -JR by default uses some simple rules to format (and unformat) an attribute for (de-)serialization. Strings and Integers are output to JSON -as is, and all other values have `.to_s` applied to them. This outputs something in all cases, but it is certainly not -correct for every situation. - -If you want to change the way an attribute is (de-)serialized you have a couple of ways. The simplest method is to create a -getter (and setter) method on the resource which overrides the attribute and apply the (un-)formatting there. For example: - -```ruby -class PersonResource < JSONAPI::Resource - attributes :name, :email, :last_login_time - - # Setter example - def email=(new_email) - @model.email = new_email.downcase - end - - # Getter example - def last_login_time - @model.last_login_time.in_time_zone(@context[:current_user].time_zone).to_s - end -end -``` - -This is simple to implement for a one off situation, but not for example if you want to apply the same formatting rules -to all DateTime fields in your system. Another issue is the attribute on the resource will always return a formatted -response, whether you want it or not. - -##### Value Formatters - -To overcome the above limitations JR uses Value Formatters. Value Formatters allow you to control the way values are -handled for an attribute. The `format` can be set per attribute as it is declared in the resource. For example: - -```ruby -class PersonResource < JSONAPI::Resource - attributes :name, :email, :spoken_languages - attribute :last_login_time, format: :date_with_utc_timezone - - # Getter/Setter for spoken_languages ... -end -``` - -A Value formatter has a `format` and an `unformat` method. Here's the base ValueFormatter and DefaultValueFormatter for -reference: - -```ruby -module JSONAPI - class ValueFormatter < Formatter - class << self - def format(raw_value) - super(raw_value) - end - - def unformat(value) - super(value) - end - ... - end - end -end - -class DefaultValueFormatter < JSONAPI::ValueFormatter - class << self - def format(raw_value) - case raw_value - when Date, Time, DateTime, ActiveSupport::TimeWithZone, BigDecimal - # Use the as_json methods added to various base classes by ActiveSupport - return raw_value.as_json - else - return raw_value - end - end - end -end -``` - -You can also create your own Value Formatter. Value Formatters must be named with the `format` name followed by -`ValueFormatter`, i.e. `DateWithUTCTimezoneValueFormatter` and derive from `JSONAPI::ValueFormatter`. It is -recommended that you create a directory for your formatters, called `formatters`. - -The `format` method is called by the `ResourceSerializer` as is serializing a resource. The format method takes the -`raw_value` parameter. `raw_value` is the value as read from the model. - -The `unformat` method is called when processing the request. Each incoming attribute (except `links`) are run through -the `unformat` method. The `unformat` method takes a `value`, which is the value as it comes in on the -request. This allows you process the incoming value to alter its state before it is stored in the model. - -###### Use a Different Default Value Formatter - -Another way to handle formatting is to set a different default value formatter. This will affect all attributes that do -not have a `format` set. You can do this by overriding the `default_attribute_options` method for a resource (or a base -resource for a system wide change). - -```ruby - def self.default_attribute_options - {format: :my_default} - end -``` - -and - -```ruby -class MyDefaultValueFormatter < DefaultValueFormatter - class << self - def format(raw_value) - case raw_value - when DateTime - return super(raw_value.in_time_zone('UTC')) - else - return super - end - end - end -end -``` - -This way all DateTime values will be formatted to display in the UTC timezone. - -#### Key Format - -By default JR uses dasherized keys as per the -[JSON API naming recommendations](http://jsonapi.org/recommendations/#naming). This can be changed by specifying a -different key formatter. - -For example, to use camel cased keys with an initial lowercase character (JSON's default) create an initializer and add -the following: - -```ruby -JSONAPI.configure do |config| - # built in key format options are :underscored_key, :camelized_key and :dasherized_key - config.json_key_format = :camelized_key -end -``` - -This will cause the serializer to use the `CamelizedKeyFormatter`. You can also create your own `KeyFormatter`, for -example: - -```ruby -class UpperCamelizedKeyFormatter < JSONAPI::KeyFormatter - class << self - def format(key) - super.camelize(:upper) - end - end -end -``` - -You would specify this in `JSONAPI.configure` as `:upper_camelized`. - -### Routing - -JR has a couple of helper methods available to assist you with setting up routes. - -##### `jsonapi_resources` - -Like `resources` in `ActionDispatch`, `jsonapi_resources` provides resourceful routes mapping between HTTP verbs and URLs -and controller actions. This will also setup mappings for relationship URLs for a resource's relationships. For example: - -```ruby -Rails.application.routes.draw do - jsonapi_resources :contacts - jsonapi_resources :phone_numbers -end -``` - -gives the following routes - -``` - Prefix Verb URI Pattern Controller#Action -contact_relationships_phone_numbers GET /contacts/:contact_id/relationships/phone-numbers(.:format) contacts#show_relationship {:relationship=>"phone_numbers"} - POST /contacts/:contact_id/relationships/phone-numbers(.:format) contacts#create_relationship {:relationship=>"phone_numbers"} - DELETE /contacts/:contact_id/relationships/phone-numbers/:keys(.:format) contacts#destroy_relationship {:relationship=>"phone_numbers"} - contact_phone_numbers GET /contacts/:contact_id/phone-numbers(.:format) phone_numbers#get_related_resources {:relationship=>"phone_numbers", :source=>"contacts"} - contacts GET /contacts(.:format) contacts#index - POST /contacts(.:format) contacts#create - contact GET /contacts/:id(.:format) contacts#show - PATCH /contacts/:id(.:format) contacts#update - PUT /contacts/:id(.:format) contacts#update - DELETE /contacts/:id(.:format) contacts#destroy - phone_number_relationships_contact GET /phone-numbers/:phone_number_id/relationships/contact(.:format) phone_numbers#show_relationship {:relationship=>"contact"} - PUT|PATCH /phone-numbers/:phone_number_id/relationships/contact(.:format) phone_numbers#update_relationship {:relationship=>"contact"} - DELETE /phone-numbers/:phone_number_id/relationships/contact(.:format) phone_numbers#destroy_relationship {:relationship=>"contact"} - phone_number_contact GET /phone-numbers/:phone_number_id/contact(.:format) contacts#get_related_resource {:relationship=>"contact", :source=>"phone_numbers"} - phone_numbers GET /phone-numbers(.:format) phone_numbers#index - POST /phone-numbers(.:format) phone_numbers#create - phone_number GET /phone-numbers/:id(.:format) phone_numbers#show - PATCH /phone-numbers/:id(.:format) phone_numbers#update - PUT /phone-numbers/:id(.:format) phone_numbers#update - DELETE /phone-numbers/:id(.:format) phone_numbers#destroy -``` - -##### `jsonapi_resource` - -Like `jsonapi_resources`, but for resources you lookup without an id. - -#### Nested Routes - -By default nested routes are created for getting related resources and manipulating relationships. You can control the -nested routes by passing a block into `jsonapi_resources` or `jsonapi_resource`. An empty block will not create -any nested routes. For example: - -```ruby -Rails.application.routes.draw do - jsonapi_resources :contacts do - end -end -``` - -gives routes that are only related to the primary resource, and none for its relationships: - -``` - Prefix Verb URI Pattern Controller#Action - contacts GET /contacts(.:format) contacts#index - POST /contacts(.:format) contacts#create - contact GET /contacts/:id(.:format) contacts#show - PATCH /contacts/:id(.:format) contacts#update - PUT /contacts/:id(.:format) contacts#update - DELETE /contacts/:id(.:format) contacts#destroy -``` - -To manually add in the nested routes you can use the `jsonapi_links`, `jsonapi_related_resources` and -`jsonapi_related_resource` inside the block. Or, you can add the default set of nested routes using the -`jsonapi_relationships` method. For example: - -```ruby -Rails.application.routes.draw do - jsonapi_resources :contacts do - jsonapi_relationships - end -end -``` - -###### `jsonapi_links` - -You can add relationship routes in with `jsonapi_links`, for example: - -```ruby -Rails.application.routes.draw do - jsonapi_resources :contacts do - jsonapi_links :phone_numbers - end -end -``` - -Gives the following routes: - -``` -contact_relationships_phone_numbers GET /contacts/:contact_id/relationships/phone-numbers(.:format) contacts#show_relationship {:relationship=>"phone_numbers"} - POST /contacts/:contact_id/relationships/phone-numbers(.:format) contacts#create_relationship {:relationship=>"phone_numbers"} - DELETE /contacts/:contact_id/relationships/phone-numbers/:keys(.:format) contacts#destroy_relationship {:relationship=>"phone_numbers"} - contacts GET /contacts(.:format) contacts#index - POST /contacts(.:format) contacts#create - contact GET /contacts/:id(.:format) contacts#show - PATCH /contacts/:id(.:format) contacts#update - PUT /contacts/:id(.:format) contacts#update - DELETE /contacts/:id(.:format) contacts#destroy - -``` - -The new routes allow you to show, create and destroy the relationships between resources. - -###### `jsonapi_related_resources` - -Creates a nested route to GET the related has_many resources. For example: - -```ruby -Rails.application.routes.draw do - jsonapi_resources :contacts do - jsonapi_related_resources :phone_numbers - end -end - -``` - -gives the following routes: - -``` - Prefix Verb URI Pattern Controller#Action -contact_phone_numbers GET /contacts/:contact_id/phone-numbers(.:format) phone_numbers#get_related_resources {:relationship=>"phone_numbers", :source=>"contacts"} - contacts GET /contacts(.:format) contacts#index - POST /contacts(.:format) contacts#create - contact GET /contacts/:id(.:format) contacts#show - PATCH /contacts/:id(.:format) contacts#update - PUT /contacts/:id(.:format) contacts#update - DELETE /contacts/:id(.:format) contacts#destroy - -``` - -A single additional route was created to allow you GET the phone numbers through the contact. - -###### `jsonapi_related_resource` - -Like `jsonapi_related_resources`, but for has_one related resources. - -```ruby -Rails.application.routes.draw do - jsonapi_resources :phone_numbers do - jsonapi_related_resource :contact - end -end -``` - -gives the following routes: - -``` - Prefix Verb URI Pattern Controller#Action -phone_number_contact GET /phone-numbers/:phone_number_id/contact(.:format) contacts#get_related_resource {:relationship=>"contact", :source=>"phone_numbers"} - phone_numbers GET /phone-numbers(.:format) phone_numbers#index - POST /phone-numbers(.:format) phone_numbers#create - phone_number GET /phone-numbers/:id(.:format) phone_numbers#show - PATCH /phone-numbers/:id(.:format) phone_numbers#update - PUT /phone-numbers/:id(.:format) phone_numbers#update - DELETE /phone-numbers/:id(.:format) phone_numbers#destroy - -``` - -### Authorization - -Currently `json-api-resources` doesn't come with built-in primitives for authorization. However multiple users of the framework have come up with different approaches, check out: - -- [jsonapi-authorization](https://github.com/venuu/jsonapi-authorization) -- [pundit-resources](https://github.com/togglepro/pundit-resources) - -Refer to the comments/discussion [here](https://github.com/cerebris/jsonapi-resources/issues/16#issuecomment-222438975) for the differences between approaches - -### Resource Caching - -To improve the response time of GET requests, JR can cache the generated JSON fragments for -Resources which are suitable. First, set `config.resource_cache` to an ActiveSupport cache store: - -```ruby -JSONAPI.configure do |config| - config.resource_cache = Rails.cache -end -``` - -Then, on each Resource you want to cache, call the `caching` method: - -```ruby -class PostResource < JSONAPI::Resource - caching -end -``` - -See the caveats section below for situations where you might not want to enable caching on particular -Resources. - -The Resource model must also have a field that is updated whenever any of the model's data changes. -The default Rails timestamps handle this pretty well, and the default cache key field is `updated_at` for this reason. -You can use an alternate field (which you are then responsible for updating) by calling the `cache_field` method: - -```ruby -class PostResource < JSONAPI::Resource - caching - cache_field :change_counter - - before_save do - if self.change_counter.nil? - self.change_counter = 1 - elsif self.changed? - self.change_counter += 1 - end - end - - after_touch do - update_attribute(:change_counter, self.change_counter + 1) - end -end -``` - -If context affects the content of the serialized result, you must define a class method `attribute_caching_context` on that Resource, which should return a different value for contexts that produce different results. In particular, if the `meta` or `fetchable_fields` methods, or any method providing the actual content of an attribute, changes depending on context, then you must provide `attribute_caching_context`. The actual value it -returns isn't important, what matters is that the value must be different if any relevant part of the context is different. - -```ruby -class PostResource < JSONAPI::Resource - caching - - attributes :title, :body, :secret_field - - def fetchable_fields - return super if context.user.superuser? - return super - [:secret_field] - end - - def meta - if context.user.can_see_creation_dates? - return { created: _model.created_at } - else - return {} - end - end - - def self.attribute_caching_context(context) - return { - admin: context.user.superuser?, - creation_date_viewer: context.user.can_see_creation_dates? - } - end -end -``` - -#### Caching Caveats - -* Models for cached Resources must update a cache key field whenever their data changes. However, if you bypass Rails and e.g. alter the database row directly without changing the `updated_at` field, the cached entry for that resource will be inaccurate. Also, `updated_at` provides a narrow race condition window; if a resource is updated twice in the same second, it's possible that only the first update will be cached. If you're concerned about this, you will need to find a way to make sure your models' cache fields change on every update, e.g. by using a unique random value or a monotonic clock. -* If an attribute's value is affected by related resources, e.g. the `spoken_languages` example above, then changes to the related resource must also touch the cache field on the resource that uses it. The `belongs_to` relation in ActiveRecord provides a `:touch` option for this purpose. -* JR does not actively clean the cache, so you must use an ActiveSupport cache that automatically expires old entries, or you will leak resources. The MemoryCache built in to Rails does this by default, but other caches will have to be configured with an `:expires_in` option and/or a cache-specific clearing mechanism. -* Similarly, if you make a substantial code change that affects a lot of serialized representations (i.e. changing the way an attribute is shown), you'll have to clear out all relevant cache entries yourself. The simplest way to do this is to run `JSONAPI.configuration.resource_cache.clear` from the console. You do not have to do this after merely adding or removing attributes; only changes that affect the actual content of attributes require manual cache clearing. -* If resource caching is enabled at all, then custom relationship methods on any resource might not always be used, even resources that are not cached. For example, if you manually define a `comments` method or `records_for_comments` method on a Resource that `has_many :comments`, you cannot expect it to be used when caching is enabled, even if you never call `caching` on that particular Resource. Instead, you should use relationship name lambdas. -* The above also applies to custom `find` or `find_by_key` methods. Instead, if you are using resource caching anywhere in your app, try overriding the `find_records` method to return an appropriate `ActiveRecord::Relation`. -* Caching relies on ActiveRecord features; you cannot enable caching on resources based on non-AR models, e.g. PORO objects or singleton resources. -* If you write a custom `ResourceSerializer` which takes new options, then you must define `config_description` to include those options if they might impact the serialized value: - -```ruby -class MySerializer < JSONAPI::ResourceSerializer - def initialize(primary_resource_klass, options = {}) - @my_special_option = options.delete(:my_special_option) - super - end - - def config_description(resource_klass) - super.merge({my_special_option: @my_special_option}) - end -end -``` - -## Configuration - -JR has a few configuration options. Some have already been mentioned above. To set configuration options create an -initializer and add the options you wish to set. All options have defaults, so you only need to set the options that -are different. The default options are shown below. - -If using custom classes (such as a CustomPaginator), be sure to require them at the top of the initializer before usage. - -```ruby -JSONAPI.configure do |config| - #:underscored_key, :camelized_key, :dasherized_key, or custom - config.json_key_format = :dasherized_key - - #:underscored_route, :camelized_route, :dasherized_route, or custom - config.route_format = :dasherized_route - - # Default Processor, used if a resource specific one is not defined. - # Must be a class - config.default_processor_klass = JSONAPI::Processor - - #:integer, :uuid, :string, or custom (provide a proc) - config.resource_key_type = :integer - - # optional request features - config.allow_include = true - config.allow_sort = true - config.allow_filter = true - - # How to handle unsupported attributes and relationships which are provided in the request - # true => raises an error - # false => allows the request to continue. A warning is included in the response meta data indicating - # the fields which were ignored. This is useful for client libraries which send extra parameters. - config.raise_if_parameters_not_allowed = true - - # :none, :offset, :paged, or a custom paginator name - config.default_paginator = :none - - # Output pagination links at top level - config.top_level_links_include_pagination = true - - config.default_page_size = 10 - config.maximum_page_size = 20 - - # Output the record count in top level meta data for find operations - config.top_level_meta_include_record_count = false - config.top_level_meta_record_count_key = :record_count - - # For :paged paginators, the following are also available - config.top_level_meta_include_page_count = false - config.top_level_meta_page_count_key = :page_count - - config.use_text_errors = false - - # List of classes that should not be rescued by the operations processor. - # For example, if you use Pundit for authorization, you might - # raise a Pundit::NotAuthorizedError at some point during operations - # processing. If you want to use Rails' `rescue_from` macro to - # catch this error and render a 403 status code, you should add - # the `Pundit::NotAuthorizedError` to the `exception_class_whitelist`. - # Subclasses of the whitelisted classes will also be whitelisted. - config.exception_class_whitelist = [] - - # If enabled, will override configuration option `exception_class_whitelist` - # and whitelist all exceptions. - config.whitelist_all_exceptions = false - - # Resource Linkage - # Controls the serialization of resource linkage for non compound documents - # NOTE: always_include_to_many_linkage_data is not currently implemented - config.always_include_to_one_linkage_data = false - - # Relationship reflection invokes the related resource when updates - # are made to a has_many relationship. By default relationship_reflection - # is turned off because it imposes a small performance penalty. - config.use_relationship_reflection = false - - # Allows transactions for creating and updating records - # Set this to false if your backend does not support transactions (e.g. Mongodb) - config.allow_transactions = true - - # Formatter Caching - # Set to false to disable caching of string operations on keys and links. - # Note that unlike the resource cache, formatter caching is always done - # internally in-memory and per-thread; no ActiveSupport::Cache is used. - config.cache_formatters = true - - # Resource cache - # An ActiveSupport::Cache::Store or similar, used by Resources with caching enabled. - # Set to `nil` (the default) to disable caching, or to `Rails.cache` to use the - # Rails cache store. - config.resource_cache = nil - - # Default resource cache field - # On Resources with caching enabled, this field will be used to check for out-of-date - # cache entries, unless overridden on a specific Resource. Defaults to "updated_at". - config.default_resource_cache_field = :updated_at - - # Resource cache digest function - # Provide a callable that returns a unique value for string inputs with - # low chance of collision. The default is SHA256 base64. - config.resource_cache_digest_function = Digest::SHA2.new.method(:base64digest) - - # Resource cache usage reporting - # Optionally provide a callable which JSONAPI will call with information about cache - # performance. Should accept three arguments: resource name, hits count, misses count. - config.resource_cache_usage_report_function = nil -end -``` +**For further usage see the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/)** ## Contributing @@ -2154,16 +48,6 @@ end 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request -### Running Tests - -To run the tests for this project: - -- `rake test` or `bundle exec rake test` - -To run a single test: - -- `bundle exec ruby -I test test/controllers/controller_test.rb -n test_type_formatting` - ## License Copyright 2014-2016 Cerebris Corporation. MIT License (see LICENSE for details). From 8c988388367fee3bad54f0352c2dc68eb53aef23 Mon Sep 17 00:00:00 2001 From: David Simon Date: Mon, 28 Nov 2016 12:15:55 -0500 Subject: [PATCH 06/60] Skip preloading of polymorphic relations, better handling of serialization with partially preloaded relations, resolves #889 (cherry picked from commit d9d9d3f) --- lib/jsonapi/cached_resource_fragment.rb | 48 ++++++++++++++----------- lib/jsonapi/resource.rb | 8 +++++ lib/jsonapi/resource_serializer.rb | 17 +++++++-- test/controllers/controller_test.rb | 30 ++++++++++++++++ 4 files changed, 81 insertions(+), 22 deletions(-) diff --git a/lib/jsonapi/cached_resource_fragment.rb b/lib/jsonapi/cached_resource_fragment.rb index 8b37cc053..67df1d9a5 100644 --- a/lib/jsonapi/cached_resource_fragment.rb +++ b/lib/jsonapi/cached_resource_fragment.rb @@ -6,14 +6,14 @@ def self.fetch_fragments(resource_klass, serializer, context, cache_ids) context_b64 = JSONAPI.configuration.resource_cache_digest_function.call(context_json) context_key = "ATTR-CTX-#{context_b64.gsub("/", "_")}" - results = self.lookup(resource_klass, serializer_config_key, context_key, cache_ids) + results = self.lookup(resource_klass, serializer_config_key, context, context_key, cache_ids) miss_ids = results.select{|k,v| v.nil? }.keys unless miss_ids.empty? find_filters = {resource_klass._primary_key => miss_ids.uniq} find_options = {context: context} resource_klass.find(find_filters, find_options).each do |resource| - (id, cr) = write(resource_klass, resource, serializer, serializer_config_key, context_key) + (id, cr) = write(resource_klass, resource, serializer, serializer_config_key, context, context_key) results[id] = cr end end @@ -29,28 +29,16 @@ def self.fetch_fragments(resource_klass, serializer, context, cache_ids) return results end - def self.from_cache_value(resource_klass, h) - new( - resource_klass, - h.fetch(:id), - h.fetch(:type), - h.fetch(:fetchable), - h.fetch(:rels, nil), - h.fetch(:links, nil), - h.fetch(:attrs, nil), - h.fetch(:meta, nil) - ) - end - - attr_reader :resource_klass, :id, :type, :fetchable_fields, :relationships, + attr_reader :resource_klass, :id, :type, :context, :fetchable_fields, :relationships, :links_json, :attributes_json, :meta_json, :preloaded_fragments - def initialize(resource_klass, id, type, fetchable_fields, relationships, + def initialize(resource_klass, id, type, context, fetchable_fields, relationships, links_json, attributes_json, meta_json) @resource_klass = resource_klass @id = id @type = type + @context = context @fetchable_fields = Set.new(fetchable_fields) # Relationships left uncompiled because we'll often want to insert included ids on retrieval @@ -76,9 +64,14 @@ def to_cache_value } end + def to_real_resource + rs = Resource.resource_for(self.type).find_by_keys([self.id], {context: self.context}) + return rs.try(:first) + end + private - def self.lookup(resource_klass, serializer_config_key, context_key, cache_ids) + def self.lookup(resource_klass, serializer_config_key, context, context_key, cache_ids) type = resource_klass._type keys = cache_ids.map do |(id, cache_key)| @@ -89,20 +82,35 @@ def self.lookup(resource_klass, serializer_config_key, context_key, cache_ids) return keys.each_with_object({}) do |key, hash| (_, id, _, _) = key if hits.has_key?(key) - hash[id] = self.from_cache_value(resource_klass, hits[key]) + hash[id] = self.from_cache_value(resource_klass, context, hits[key]) else hash[id] = nil end end end - def self.write(resource_klass, resource, serializer, serializer_config_key, context_key) + def self.from_cache_value(resource_klass, context, h) + new( + resource_klass, + h.fetch(:id), + h.fetch(:type), + context, + h.fetch(:fetchable), + h.fetch(:rels, nil), + h.fetch(:links, nil), + h.fetch(:attrs, nil), + h.fetch(:meta, nil) + ) + end + + def self.write(resource_klass, resource, serializer, serializer_config_key, context, context_key) (id, cache_key) = resource.cache_id json = serializer.object_hash(resource) # No inclusions passed to object_hash cr = self.new( resource_klass, json['id'], json['type'], + context, resource.fetchable_fields, json['relationships'], json['links'], diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index af4ded28e..a5bb1d791 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -1133,8 +1133,15 @@ def preload_included_fragments(resources, records, serializer, options) # For each step on the path, figure out what the actual table name/alias in the join # will be, and include the primary key of that table in our list of fields to select + non_polymorphic = true path.each do |elem| relationship = klass._relationships[elem] + if relationship.polymorphic + # Can't preload through a polymorphic belongs_to association, ResourceSerializer + # will just have to bypass the cache and load the real Resource. + non_polymorphic = false + break + end assocs_path << relationship.relation_name(options).to_sym # Converts [:a, :b, :c] to Rails-style { :a => { :b => :c }} ar_hash = assocs_path.reverse.reduce{|memo, step| { step => memo } } @@ -1148,6 +1155,7 @@ def preload_included_fragments(resources, records, serializer, options) klass = relationship.resource_klass pluck_attrs << table[klass._primary_key] end + next unless non_polymorphic # Pre-fill empty hashes for each resource up to the end of the path. # This allows us to later distinguish between a preload that returned nothing diff --git a/lib/jsonapi/resource_serializer.rb b/lib/jsonapi/resource_serializer.rb index 1bde2ab0d..28e52f3f9 100644 --- a/lib/jsonapi/resource_serializer.rb +++ b/lib/jsonapi/resource_serializer.rb @@ -298,8 +298,11 @@ def cached_relationships_hash(source, include_directives) h = source.relationships || {} return h unless include_directives.has_key?(:include_related) - relationships = source.resource_klass._relationships.select{|k,v| source.fetchable_fields.include?(k) } + relationships = source.resource_klass._relationships.select do |k,v| + source.fetchable_fields.include?(k) + end + real_res = nil relationships.each do |rel_name, relationship| key = @key_formatter.format(rel_name) to_many = relationship.is_a? JSONAPI::Relationship::ToMany @@ -310,7 +313,17 @@ def cached_relationships_hash(source, include_directives) h[key][:data] = to_many ? [] : nil end - source.preloaded_fragments[key].each do |id, f| + fragments = source.preloaded_fragments[key] + if fragments.nil? + # The resources we want were not preloaded, we'll have to bypass the cache. + # This happens when including through belongs_to polymorphic relationships + if real_res.nil? + real_res = source.to_real_resource + end + relation_resources = [real_res.public_send(rel_name)].flatten(1).compact + fragments = relation_resources.map{|r| [r.id, r]}.to_h + end + fragments.each do |id, f| add_resource(f, ia) if h.has_key?(key) diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index 38baf07c6..b6e59f537 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -1923,6 +1923,36 @@ def test_tags_show_multiple_with_nonexistent_ids_at_the_beginning end end +class PicturesControllerTest < ActionController::TestCase + def test_pictures_index + assert_cacheable_get :index + assert_response :success + assert_equal 3, json_response['data'].size + end + + def test_pictures_index_with_polymorphic_include_one_level + assert_cacheable_get :index, params: {include: 'imageable'} + assert_response :success + assert_equal 3, json_response['data'].size + assert_equal 2, json_response['included'].size + end +end + +class DocumentsControllerTest < ActionController::TestCase + def test_documents_index + assert_cacheable_get :index + assert_response :success + assert_equal 1, json_response['data'].size + end + + def test_documents_index_with_polymorphic_include_one_level + assert_cacheable_get :index, params: {include: 'pictures'} + assert_response :success + assert_equal 1, json_response['data'].size + assert_equal 1, json_response['included'].size + end +end + class ExpenseEntriesControllerTest < ActionController::TestCase def setup JSONAPI.configuration.json_key_format = :camelized_key From 7158e52965199fde01df194eb2a56888a0c3328b Mon Sep 17 00:00:00 2001 From: Pete Cruz Date: Sun, 30 Oct 2016 14:26:11 -0400 Subject: [PATCH 07/60] Rescue JSON parsing error and return all exceptions from the parser in `_parser_exception` (cherry picked from commit e144f80) --- lib/jsonapi/error_codes.rb | 1 + lib/jsonapi/exceptions.rb | 26 ++++++++++++++++++ lib/jsonapi/mime_types.rb | 17 +++++++++--- lib/jsonapi/request_parser.rb | 1 + test/integration/requests/request_test.rb | 33 +++++++++++++++++++++++ 5 files changed, 75 insertions(+), 3 deletions(-) diff --git a/lib/jsonapi/error_codes.rb b/lib/jsonapi/error_codes.rb index 290ee6189..35f309bc7 100644 --- a/lib/jsonapi/error_codes.rb +++ b/lib/jsonapi/error_codes.rb @@ -20,6 +20,7 @@ module JSONAPI INVALID_FILTERS_SYNTAX = '120' SAVE_FAILED = '121' INVALID_DATA_FORMAT = '122' + BAD_REQUEST = '400' FORBIDDEN = '403' RECORD_NOT_FOUND = '404' NOT_ACCEPTABLE = '406' diff --git a/lib/jsonapi/exceptions.rb b/lib/jsonapi/exceptions.rb index 2d220e756..29b66b766 100644 --- a/lib/jsonapi/exceptions.rb +++ b/lib/jsonapi/exceptions.rb @@ -119,6 +119,32 @@ def errors end end + class BadRequest < Error + def initialize(exception) + @exception = exception + end + + def errors + [JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.bad_request.title', + default: 'Bad Request'), + detail: I18n.translate('jsonapi-resources.exceptions.bad_request.detail', + default: @exception))] + end + end + + class InvalidRequestFormat < Error + def errors + [JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_request_format.title', + default: 'Bad Request'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_request_format.detail', + default: 'Request must be a hash'))] + end + end + class ToManySetReplacementForbidden < Error def errors [JSONAPI::Error.new(code: JSONAPI::FORBIDDEN, diff --git a/lib/jsonapi/mime_types.rb b/lib/jsonapi/mime_types.rb index f8bde565e..78e8f1d4f 100644 --- a/lib/jsonapi/mime_types.rb +++ b/lib/jsonapi/mime_types.rb @@ -1,3 +1,5 @@ +require 'json' + module JSONAPI MEDIA_TYPE = 'application/vnd.api+json' @@ -19,9 +21,18 @@ def self.install def self.parser lambda do |body| - data = JSON.parse(body) - data = {:_json => data} unless data.is_a?(Hash) - data.with_indifferent_access + begin + data = JSON.parse(body) + if data.is_a?(Hash) + data.with_indifferent_access + else + fail JSONAPI::Exceptions::InvalidRequestFormat.new + end + rescue JSON::ParserError => e + { _parser_exception: JSONAPI::Exceptions::BadRequest.new(e.to_s) } + rescue => e + { _parser_exception: e } + end end end end diff --git a/lib/jsonapi/request_parser.rb b/lib/jsonapi/request_parser.rb index 2929a696a..2e0faacfa 100644 --- a/lib/jsonapi/request_parser.rb +++ b/lib/jsonapi/request_parser.rb @@ -34,6 +34,7 @@ def setup_action(params) setup_action_method_name = "setup_#{params[:action]}_action" if respond_to?(setup_action_method_name) + raise params[:_parser_exception] if params[:_parser_exception] send(setup_action_method_name, params) end rescue ActionController::ParameterMissing => e diff --git a/test/integration/requests/request_test.rb b/test/integration/requests/request_test.rb index 99885de21..dc10b78e8 100644 --- a/test/integration/requests/request_test.rb +++ b/test/integration/requests/request_test.rb @@ -353,6 +353,39 @@ def test_put_content_type assert_match JSONAPI::MEDIA_TYPE, headers['Content-Type'] end + def test_put_valid_json + put '/posts/3', params: '{"data": { "type": "posts", "id": "3", "attributes": { "title": "A great new Post" } } }', + headers: { + 'CONTENT_TYPE' => JSONAPI::MEDIA_TYPE, + 'Accept' => JSONAPI::MEDIA_TYPE + } + + assert_equal 200, status + end + + def test_put_invalid_json + put '/posts/3', params: '{"data": { "type": "posts", "id": "3" "attributes": { "title": "A great new Post" } } }', + headers: { + 'CONTENT_TYPE' => JSONAPI::MEDIA_TYPE, + 'Accept' => JSONAPI::MEDIA_TYPE + } + + assert_equal 400, status + assert_equal 'Bad Request', json_response['errors'][0]['title'] + assert_match 'unexpected token at', json_response['errors'][0]['detail'] + end + + def test_put_valid_json_but_array + put '/posts/3', params: '[{"data": { "type": "posts", "id": "3", "attributes": { "title": "A great new Post" } } }]', + headers: { + 'CONTENT_TYPE' => JSONAPI::MEDIA_TYPE, + 'Accept' => JSONAPI::MEDIA_TYPE + } + + assert_equal 400, status + assert_equal 'Request must be a hash', json_response['errors'][0]['detail'] + end + def test_patch_content_type patch '/posts/3', params: { From d7a2380435847ff904a3fc40851ffb1bbcc0bdc7 Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Thu, 27 Oct 2016 16:44:16 -0400 Subject: [PATCH 08/60] Add facility to override error object members in JR Exceptions (cherry picked from commit 854873c) --- lib/jsonapi/exceptions.rb | 456 +++++++++++++++++++++----------------- lib/jsonapi/paginator.rb | 4 +- 2 files changed, 254 insertions(+), 206 deletions(-) diff --git a/lib/jsonapi/exceptions.rb b/lib/jsonapi/exceptions.rb index 29b66b766..cf77dfd12 100644 --- a/lib/jsonapi/exceptions.rb +++ b/lib/jsonapi/exceptions.rb @@ -1,6 +1,16 @@ module JSONAPI module Exceptions class Error < RuntimeError + attr :error_object_overrides + + def initialize(error_object_overrides = {}) + @error_object_overrides = error_object_overrides + end + + def create_error_object(error_defaults) + JSONAPI::Error.new(error_defaults.merge(error_object_overrides)) + end + def errors # :nocov: raise NotImplementedError, "Subclass of Error must implement errors method" @@ -11,8 +21,9 @@ def errors class InternalServerError < Error attr_accessor :exception - def initialize(exception) + def initialize(exception, error_object_overrides = {}) @exception = exception + super(error_object_overrides) end def errors @@ -22,100 +33,109 @@ def errors meta[:backtrace] = exception.backtrace end - [JSONAPI::Error.new(code: JSONAPI::INTERNAL_SERVER_ERROR, - status: :internal_server_error, - title: I18n.t('jsonapi-resources.exceptions.internal_server_error.title', - default: 'Internal Server Error'), - detail: I18n.t('jsonapi-resources.exceptions.internal_server_error.detail', + [create_error_object(code: JSONAPI::INTERNAL_SERVER_ERROR, + status: :internal_server_error, + title: I18n.t('jsonapi-resources.exceptions.internal_server_error.title', default: 'Internal Server Error'), - meta: meta)] + detail: I18n.t('jsonapi-resources.exceptions.internal_server_error.detail', + default: 'Internal Server Error'), + meta: meta)] end end class InvalidResource < Error attr_accessor :resource - def initialize(resource) + + def initialize(resource, error_object_overrides = {}) @resource = resource + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_RESOURCE, - status: :bad_request, - title: I18n.t('jsonapi-resources.exceptions.invalid_resource.title', - default: 'Invalid resource'), - detail: I18n.t('jsonapi-resources.exceptions.invalid_resource.detail', - default: "#{resource} is not a valid resource.", resource: resource))] + [create_error_object(code: JSONAPI::INVALID_RESOURCE, + status: :bad_request, + title: I18n.t('jsonapi-resources.exceptions.invalid_resource.title', + default: 'Invalid resource'), + detail: I18n.t('jsonapi-resources.exceptions.invalid_resource.detail', + default: "#{resource} is not a valid resource.", resource: resource))] end end class RecordNotFound < Error attr_accessor :id - def initialize(id) + + def initialize(id, error_object_overrides = {}) @id = id + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::RECORD_NOT_FOUND, - status: :not_found, - title: I18n.translate('jsonapi-resources.exceptions.record_not_found.title', - default: 'Record not found'), - detail: I18n.translate('jsonapi-resources.exceptions.record_not_found.detail', - default: "The record identified by #{id} could not be found.", id: id))] + [create_error_object(code: JSONAPI::RECORD_NOT_FOUND, + status: :not_found, + title: I18n.translate('jsonapi-resources.exceptions.record_not_found.title', + default: 'Record not found'), + detail: I18n.translate('jsonapi-resources.exceptions.record_not_found.detail', + default: "The record identified by #{id} could not be found.", id: id))] end end class UnsupportedMediaTypeError < Error attr_accessor :media_type - def initialize(media_type) + + def initialize(media_type, error_object_overrides = {}) @media_type = media_type + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::UNSUPPORTED_MEDIA_TYPE, - status: :unsupported_media_type, - title: I18n.translate('jsonapi-resources.exceptions.unsupported_media_type.title', - default: 'Unsupported media type'), - detail: I18n.translate('jsonapi-resources.exceptions.unsupported_media_type.detail', - default: "All requests that create or update must use the '#{JSONAPI::MEDIA_TYPE}' Content-Type. This request specified '#{media_type}'.", - needed_media_type: JSONAPI::MEDIA_TYPE, - media_type: media_type))] + [create_error_object(code: JSONAPI::UNSUPPORTED_MEDIA_TYPE, + status: :unsupported_media_type, + title: I18n.translate('jsonapi-resources.exceptions.unsupported_media_type.title', + default: 'Unsupported media type'), + detail: I18n.translate('jsonapi-resources.exceptions.unsupported_media_type.detail', + default: "All requests that create or update must use the '#{JSONAPI::MEDIA_TYPE}' Content-Type. This request specified '#{media_type}'.", + needed_media_type: JSONAPI::MEDIA_TYPE, + media_type: media_type))] end end class NotAcceptableError < Error attr_accessor :media_type - def initialize(media_type) + def initialize(media_type, error_object_overrides = {}) @media_type = media_type + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::NOT_ACCEPTABLE, - status: :not_acceptable, - title: I18n.translate('jsonapi-resources.exceptions.not_acceptable.title', - default: 'Not acceptable'), - detail: I18n.translate('jsonapi-resources.exceptions.not_acceptable.detail', - default: "All requests must use the '#{JSONAPI::MEDIA_TYPE}' Accept without media type parameters. This request specified '#{media_type}'.", - needed_media_type: JSONAPI::MEDIA_TYPE, - media_type: media_type))] + [create_error_object(code: JSONAPI::NOT_ACCEPTABLE, + status: :not_acceptable, + title: I18n.translate('jsonapi-resources.exceptions.not_acceptable.title', + default: 'Not acceptable'), + detail: I18n.translate('jsonapi-resources.exceptions.not_acceptable.detail', + default: "All requests must use the '#{JSONAPI::MEDIA_TYPE}' Accept without media type parameters. This request specified '#{media_type}'.", + needed_media_type: JSONAPI::MEDIA_TYPE, + media_type: media_type))] end end class HasManyRelationExists < Error attr_accessor :id - def initialize(id) + + def initialize(id, error_object_overrides = {}) @id = id + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::RELATION_EXISTS, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.has_many_relation.title', - default: 'Relation exists'), - detail: I18n.translate('jsonapi-resources.exceptions.has_many_relation.detail', - default: "The relation to #{id} already exists.", - id: id))] + [create_error_object(code: JSONAPI::RELATION_EXISTS, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.has_many_relation.title', + default: 'Relation exists'), + detail: I18n.translate('jsonapi-resources.exceptions.has_many_relation.detail', + default: "The relation to #{id} already exists.", + id: id))] end end @@ -147,201 +167,219 @@ def errors class ToManySetReplacementForbidden < Error def errors - [JSONAPI::Error.new(code: JSONAPI::FORBIDDEN, - status: :forbidden, - title: I18n.translate('jsonapi-resources.exceptions.to_many_set_replacement_forbidden.title', - default: 'Complete replacement forbidden'), - detail: I18n.translate('jsonapi-resources.exceptions.to_many_set_replacement_forbidden.detail', - default: 'Complete replacement forbidden for this relationship'))] + [create_error_object(code: JSONAPI::FORBIDDEN, + status: :forbidden, + title: I18n.translate('jsonapi-resources.exceptions.to_many_set_replacement_forbidden.title', + default: 'Complete replacement forbidden'), + detail: I18n.translate('jsonapi-resources.exceptions.to_many_set_replacement_forbidden.detail', + default: 'Complete replacement forbidden for this relationship'))] end end class InvalidFiltersSyntax < Error attr_accessor :filters - def initialize(filters) + + def initialize(filters, error_object_overrides = {}) @filters = filters + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_FILTERS_SYNTAX, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_filter_syntax.title', - default: 'Invalid filters syntax'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_filter_syntax.detail', - default: "#{filters} is not a valid syntax for filtering.", - filters: filters))] + [create_error_object(code: JSONAPI::INVALID_FILTERS_SYNTAX, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_filter_syntax.title', + default: 'Invalid filters syntax'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_filter_syntax.detail', + default: "#{filters} is not a valid syntax for filtering.", + filters: filters))] end end class FilterNotAllowed < Error attr_accessor :filter - def initialize(filter) + + def initialize(filter, error_object_overrides = {}) @filter = filter + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::FILTER_NOT_ALLOWED, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.filter_not_allowed.title', - default: 'Filter not allowed'), - detail: I18n.translate('jsonapi-resources.exceptions.filter_not_allowed.detail', - default: "#{filter} is not allowed.", filter: filter))] + [create_error_object(code: JSONAPI::FILTER_NOT_ALLOWED, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.filter_not_allowed.title', + default: 'Filter not allowed'), + detail: I18n.translate('jsonapi-resources.exceptions.filter_not_allowed.detail', + default: "#{filter} is not allowed.", filter: filter))] end end class InvalidFilterValue < Error attr_accessor :filter, :value - def initialize(filter, value) + + def initialize(filter, value, error_object_overrides = {}) @filter = filter @value = value + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_FILTER_VALUE, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_filter_value.title', - default: 'Invalid filter value'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_filter_value.detail', - default: "#{value} is not a valid value for #{filter}.", - value: value, filter: filter))] + [create_error_object(code: JSONAPI::INVALID_FILTER_VALUE, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_filter_value.title', + default: 'Invalid filter value'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_filter_value.detail', + default: "#{value} is not a valid value for #{filter}.", + value: value, filter: filter))] end end class InvalidFieldValue < Error attr_accessor :field, :value - def initialize(field, value) + + def initialize(field, value, error_object_overrides = {}) @field = field @value = value + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_FIELD_VALUE, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_field_value.title', - default: 'Invalid field value'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_field_value.detail', - default: "#{value} is not a valid value for #{field}.", - value: value, field: field))] + [create_error_object(code: JSONAPI::INVALID_FIELD_VALUE, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_field_value.title', + default: 'Invalid field value'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_field_value.detail', + default: "#{value} is not a valid value for #{field}.", + value: value, field: field))] end end class InvalidFieldFormat < Error def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_FIELD_FORMAT, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_field_format.title', - default: 'Invalid field format'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_field_format.detail', - default: 'Fields must specify a type.'))] + [create_error_object(code: JSONAPI::INVALID_FIELD_FORMAT, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_field_format.title', + default: 'Invalid field format'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_field_format.detail', + default: 'Fields must specify a type.'))] end end class InvalidDataFormat < Error def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_DATA_FORMAT, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_data_format.title', - default: 'Invalid data format'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_data_format.detail', - default: 'Data must be a hash.'))] + [create_error_object(code: JSONAPI::INVALID_DATA_FORMAT, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_data_format.title', + default: 'Invalid data format'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_data_format.detail', + default: 'Data must be a hash.'))] end end class InvalidLinksObject < Error def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_LINKS_OBJECT, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_links_object.title', - default: 'Invalid Links Object'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_links_object.detail', - default: 'Data is not a valid Links Object.'))] + [create_error_object(code: JSONAPI::INVALID_LINKS_OBJECT, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_links_object.title', + default: 'Invalid Links Object'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_links_object.detail', + default: 'Data is not a valid Links Object.'))] end end class TypeMismatch < Error attr_accessor :type - def initialize(type) + + def initialize(type, error_object_overrides = {}) @type = type + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::TYPE_MISMATCH, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.type_mismatch.title', - default: 'Type Mismatch'), - detail: I18n.translate('jsonapi-resources.exceptions.type_mismatch.detail', - default: "#{type} is not a valid type for this operation.", type: type))] + [create_error_object(code: JSONAPI::TYPE_MISMATCH, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.type_mismatch.title', + default: 'Type Mismatch'), + detail: I18n.translate('jsonapi-resources.exceptions.type_mismatch.detail', + default: "#{type} is not a valid type for this operation.", type: type))] end end class InvalidField < Error attr_accessor :field, :type - def initialize(type, field) + + def initialize(type, field, error_object_overrides = {}) @field = field @type = type + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_FIELD, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_field.title', - default: 'Invalid field'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_field.detail', - default: "#{field} is not a valid field for #{type}.", - field: field, type: type))] + [create_error_object(code: JSONAPI::INVALID_FIELD, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_field.title', + default: 'Invalid field'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_field.detail', + default: "#{field} is not a valid field for #{type}.", + field: field, type: type))] end end class InvalidInclude < Error attr_accessor :relationship, :resource - def initialize(resource, relationship) + + def initialize(resource, relationship, error_object_overrides = {}) @resource = resource @relationship = relationship + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_INCLUDE, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_include.title', - default: 'Invalid field'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_include.detail', - default: "#{relationship} is not a valid relationship of #{resource}", - relationship: relationship, resource: resource))] + [create_error_object(code: JSONAPI::INVALID_INCLUDE, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_include.title', + default: 'Invalid field'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_include.detail', + default: "#{relationship} is not a valid relationship of #{resource}", + relationship: relationship, resource: resource))] end end class InvalidSortCriteria < Error attr_accessor :sort_criteria, :resource - def initialize(resource, sort_criteria) + + def initialize(resource, sort_criteria, error_object_overrides = {}) @resource = resource @sort_criteria = sort_criteria + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_SORT_CRITERIA, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_sort_criteria.title', - default: 'Invalid sort criteria'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_sort_criteria.detail', - default: "#{sort_criteria} is not a valid sort criteria for #{resource}", - sort_criteria: sort_criteria, resource: resource))] + [create_error_object(code: JSONAPI::INVALID_SORT_CRITERIA, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_sort_criteria.title', + default: 'Invalid sort criteria'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_sort_criteria.detail', + default: "#{sort_criteria} is not a valid sort criteria for #{resource}", + sort_criteria: sort_criteria, resource: resource))] end end class ParametersNotAllowed < Error attr_accessor :params - def initialize(params) + + def initialize(params, error_object_overrides = {}) @params = params + super(error_object_overrides) end def errors params.collect do |param| - JSONAPI::Error.new(code: JSONAPI::PARAM_NOT_ALLOWED, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.parameters_not_allowed.title', - default: 'Param not allowed'), - detail: I18n.translate('jsonapi-resources.exceptions.parameters_not_allowed.detail', - default: "#{param} is not allowed.", param: param)) + create_error_object(code: JSONAPI::PARAM_NOT_ALLOWED, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.parameters_not_allowed.title', + default: 'Param not allowed'), + detail: I18n.translate('jsonapi-resources.exceptions.parameters_not_allowed.detail', + default: "#{param} is not allowed.", param: param)) end end @@ -349,71 +387,78 @@ def errors class ParameterMissing < Error attr_accessor :param - def initialize(param) + + def initialize(param, error_object_overrides = {}) @param = param + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::PARAM_MISSING, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.parameter_missing.title', - default: 'Missing Parameter'), - detail: I18n.translate('jsonapi-resources.exceptions.parameter_missing.detail', - default: "The required parameter, #{param}, is missing.", param: param))] + [create_error_object(code: JSONAPI::PARAM_MISSING, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.parameter_missing.title', + default: 'Missing Parameter'), + detail: I18n.translate('jsonapi-resources.exceptions.parameter_missing.detail', + default: "The required parameter, #{param}, is missing.", param: param))] end end class KeyNotIncludedInURL < Error attr_accessor :key - def initialize(key) + + def initialize(key, error_object_overrides = {}) @key = key + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::KEY_NOT_INCLUDED_IN_URL, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.key_not_included_in_url.title', - default: 'Key is not included in URL'), - detail: I18n.translate('jsonapi-resources.exceptions.key_not_included_in_url.detail', - default: "The URL does not support the key #{key}", - key: key))] + [create_error_object(code: JSONAPI::KEY_NOT_INCLUDED_IN_URL, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.key_not_included_in_url.title', + default: 'Key is not included in URL'), + detail: I18n.translate('jsonapi-resources.exceptions.key_not_included_in_url.detail', + default: "The URL does not support the key #{key}", + key: key))] end end class MissingKey < Error def errors - [JSONAPI::Error.new(code: JSONAPI::KEY_ORDER_MISMATCH, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.missing_key.title', - default: 'A key is required'), - detail: I18n.translate('jsonapi-resources.exceptions.missing_key.detail', - default: 'The resource object does not contain a key.'))] + [create_error_object(code: JSONAPI::KEY_ORDER_MISMATCH, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.missing_key.title', + default: 'A key is required'), + detail: I18n.translate('jsonapi-resources.exceptions.missing_key.detail', + default: 'The resource object does not contain a key.'))] end end class RecordLocked < Error attr_accessor :message - def initialize(message) + + def initialize(message, error_object_overrides = {}) @message = message + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::LOCKED, - status: :locked, - title: I18n.translate('jsonapi-resources.exceptions.record_locked.title', - default: 'Locked resource'), - detail: "#{message}")] + [create_error_object(code: JSONAPI::LOCKED, + status: :locked, + title: I18n.translate('jsonapi-resources.exceptions.record_locked.title', + default: 'Locked resource'), + detail: "#{message}")] end end class ValidationErrors < Error attr_reader :error_messages, :error_metadata, :resource_relationships - def initialize(resource) + def initialize(resource, error_object_overrides = {}) @error_messages = resource.model_error_messages @error_metadata = resource.validation_error_metadata @resource_relationships = resource.class._relationships.keys @key_formatter = JSONAPI.configuration.key_formatter + super(error_object_overrides) end def format_key(key) @@ -429,17 +474,17 @@ def errors private def json_api_error(attr_key, message) - JSONAPI::Error.new(code: JSONAPI::VALIDATION_ERROR, - status: :unprocessable_entity, - title: message, - detail: "#{format_key(attr_key)} - #{message}", - source: { pointer: pointer(attr_key) }, - meta: metadata_for(attr_key, message)) + create_error_object(code: JSONAPI::VALIDATION_ERROR, + status: :unprocessable_entity, + title: message, + detail: "#{format_key(attr_key)} - #{message}", + source: { pointer: pointer(attr_key) }, + meta: metadata_for(attr_key, message)) end def metadata_for(attr_key, message) return if error_metadata.nil? - error_metadata[attr_key] ? error_metadata[attr_key][message] : nil + error_metadata[attr_key] ? error_metadata[attr_key][message] : nil end def pointer(attr_or_relationship_name) @@ -454,61 +499,64 @@ def pointer(attr_or_relationship_name) class SaveFailed < Error def errors - [JSONAPI::Error.new(code: JSONAPI::SAVE_FAILED, - status: :unprocessable_entity, - title: I18n.translate('jsonapi-resources.exceptions.save_failed.title', - default: 'Save failed or was cancelled'), - detail: I18n.translate('jsonapi-resources.exceptions.save_failed.detail', - default: 'Save failed or was cancelled'))] + [create_error_object(code: JSONAPI::SAVE_FAILED, + status: :unprocessable_entity, + title: I18n.translate('jsonapi-resources.exceptions.save_failed.title', + default: 'Save failed or was cancelled'), + detail: I18n.translate('jsonapi-resources.exceptions.save_failed.detail', + default: 'Save failed or was cancelled'))] end end class InvalidPageObject < Error def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_PAGE_OBJECT, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_page_object.title', - default: 'Invalid Page Object'), - detail: I18n.translate('jsonapi-resources.exceptions.invalid_page_object.detail', - default: 'Invalid Page Object.'))] + [create_error_object(code: JSONAPI::INVALID_PAGE_OBJECT, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_page_object.title', + default: 'Invalid Page Object'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_page_object.detail', + default: 'Invalid Page Object.'))] end end class PageParametersNotAllowed < Error attr_accessor :params - def initialize(params) + + def initialize(params, error_object_overrides = {}) @params = params + super(error_object_overrides) end def errors params.collect do |param| - JSONAPI::Error.new(code: JSONAPI::PARAM_NOT_ALLOWED, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.page_parameters_not_allowed.title', - default: 'Page parameter not allowed'), - detail: I18n.translate('jsonapi-resources.exceptions.page_parameters_not_allowed.detail', - default: "#{param} is not an allowed page parameter.", - param: param)) + create_error_object(code: JSONAPI::PARAM_NOT_ALLOWED, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.page_parameters_not_allowed.title', + default: 'Page parameter not allowed'), + detail: I18n.translate('jsonapi-resources.exceptions.page_parameters_not_allowed.detail', + default: "#{param} is not an allowed page parameter.", + param: param)) end end end class InvalidPageValue < Error attr_accessor :page, :value - def initialize(page, value, msg = nil) + + def initialize(page, value, error_object_overrides = {}) @page = page @value = value - @msg = msg || I18n.translate('jsonapi-resources.exceptions.invalid_page_value.detail', - default: "#{value} is not a valid value for #{page} page parameter.", - value: value, page: page) + super(error_object_overrides) end def errors - [JSONAPI::Error.new(code: JSONAPI::INVALID_PAGE_VALUE, - status: :bad_request, - title: I18n.translate('jsonapi-resources.exceptions.invalid_page_value.title', - default: 'Invalid page value'), - detail: @msg)] + [create_error_object(code: JSONAPI::INVALID_PAGE_VALUE, + status: :bad_request, + title: I18n.translate('jsonapi-resources.exceptions.invalid_page_value.title', + default: 'Invalid page value'), + detail: I18n.translate('jsonapi-resources.exceptions.invalid_page_value.detail', + default: "#{value} is not a valid value for #{page} page parameter.", + value: value, page: page))] end end end diff --git a/lib/jsonapi/paginator.rb b/lib/jsonapi/paginator.rb index 3ad00abbe..53f8fbbe4 100644 --- a/lib/jsonapi/paginator.rb +++ b/lib/jsonapi/paginator.rb @@ -110,7 +110,7 @@ def verify_pagination_params fail JSONAPI::Exceptions::InvalidPageValue.new(:limit, @limit) elsif @limit > JSONAPI.configuration.maximum_page_size fail JSONAPI::Exceptions::InvalidPageValue.new(:limit, @limit, - "Limit exceeds maximum page size of #{JSONAPI.configuration.maximum_page_size}.") + detail: "Limit exceeds maximum page size of #{JSONAPI.configuration.maximum_page_size}.") end if @offset < 0 @@ -199,7 +199,7 @@ def verify_pagination_params fail JSONAPI::Exceptions::InvalidPageValue.new(:size, @size) elsif @size > JSONAPI.configuration.maximum_page_size fail JSONAPI::Exceptions::InvalidPageValue.new(:size, @size, - "size exceeds maximum page size of #{JSONAPI.configuration.maximum_page_size}.") + detail: "size exceeds maximum page size of #{JSONAPI.configuration.maximum_page_size}.") end if @number < 1 From 506c86017e97286d15a7d222ca89a15bc7fd3ade Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Mon, 19 Dec 2016 14:20:06 -0500 Subject: [PATCH 09/60] Fix 933 - Sort with has one include --- lib/jsonapi/resource.rb | 3 +-- lib/jsonapi/resource_serializer.rb | 34 +++++++++++++++++++++++------ test/controllers/controller_test.rb | 21 +++++++++++++++++- test/fixtures/active_record.rb | 4 ---- 4 files changed, 48 insertions(+), 14 deletions(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index a5bb1d791..58e930f82 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -1102,7 +1102,6 @@ def preload_included_fragments(resources, records, serializer, options) include_directives = options[:include_directives] return unless include_directives - relevant_options = options.except(:include_directives, :order, :paginator) context = options[:context] # For each association, including indirect associations, find the target record ids. @@ -1196,7 +1195,7 @@ def preload_included_fragments(resources, records, serializer, options) .map(&:last) .reject{|id| target_resources[klass.name].has_key?(id) } .uniq - found = klass.find({klass._primary_key => sub_res_ids}, relevant_options) + found = klass.find({klass._primary_key => sub_res_ids}, context: options[:context]) target_resources[klass.name].merge! found.map{|r| [r.id, r] }.to_h end diff --git a/lib/jsonapi/resource_serializer.rb b/lib/jsonapi/resource_serializer.rb index 28e52f3f9..62a23c1d7 100644 --- a/lib/jsonapi/resource_serializer.rb +++ b/lib/jsonapi/resource_serializer.rb @@ -50,15 +50,35 @@ def serialize_to_hash(source) @included_objects = {} - process_primary(source, @include_directives.include_directives) + process_source_objects(source, @include_directives.include_directives) - included_objects = [] primary_objects = [] + + # pull the processed objects corresponding to the source objects. Ensures we preserve order. + if is_resource_collection + source.each do |primary| + if primary.id + case primary + when CachedResourceFragment then primary_objects.push(@included_objects[primary.type][primary.id][:object_hash]) + when Resource then primary_objects.push(@included_objects[primary.class._type][primary.id][:object_hash]) + else raise "Unknown source type #{primary.inspect}" + end + end + end + else + if source.try(:id) + case source + when CachedResourceFragment then primary_objects.push(@included_objects[source.type][source.id][:object_hash]) + when Resource then primary_objects.push(@included_objects[source.class._type][source.id][:object_hash]) + else raise "Unknown source type #{source.inspect}" + end + end + end + + included_objects = [] @included_objects.each_value do |objects| objects.each_value do |object| - if object[:primary] - primary_objects.push(object[:object_hash]) - else + unless object[:primary] included_objects.push(object[:object_hash]) end end @@ -168,9 +188,9 @@ def object_hash(source, include_directives = {}) # requested includes. Fields are controlled fields option for each resource type, such # as fields: { people: [:id, :email, :comments], posts: [:id, :title, :author], comments: [:id, :body, :post]} # The fields options controls both fields and included links references. - def process_primary(source, include_directives) + def process_source_objects(source, include_directives) if source.respond_to?(:to_ary) - source.each { |resource| process_primary(resource, include_directives) } + source.each { |resource| process_source_objects(resource, include_directives) } else return {} if source.nil? add_resource(source, include_directives, true) diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index b6e59f537..adea95ea4 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -423,7 +423,7 @@ def test_sorting_by_relationship_field assert_cacheable_get :index, params: {sort: 'author.name'} assert_response :success - assert json_response['data'].length > 10, 'there are enough recordsto show sort' + assert json_response['data'].length > 10, 'there are enough records to show sort' assert_equal '17', json_response['data'][0]['id'], 'nil is at the top' assert_equal post.id.to_s, json_response['data'][1]['id'], 'alphabetically first user is second' end @@ -438,6 +438,16 @@ def test_desc_sorting_by_relationship_field assert_equal post.id.to_s, json_response['data'][-2]['id'], 'alphabetically first user is second last' end + def test_sorting_by_relationship_field_include + post = create_alphabetically_first_user_and_post + assert_cacheable_get :index, params: {include: 'author', sort: 'author.name'} + + assert_response :success + assert json_response['data'].length > 10, 'there are enough records to show sort' + assert_equal '17', json_response['data'][0]['id'], 'nil is at the top' + assert_equal post.id.to_s, json_response['data'][1]['id'], 'alphabetically first user is second' + end + def test_invalid_sort_param assert_cacheable_get :index, params: {sort: 'asdfg'} @@ -1921,6 +1931,15 @@ def test_tags_show_multiple_with_nonexistent_ids_at_the_beginning assert_response :bad_request assert_match /99,9,100 is not a valid value for id/, response.body end + + def test_nested_includes_sort + assert_cacheable_get :index, params: {filter: {id: '6,7,8,9'}, + include: 'posts.tags,posts.author.posts', + sort: 'name'} + assert_response :success + assert_equal 4, json_response['data'].size + assert_equal 3, json_response['included'].size + end end class PicturesControllerTest < ActionController::TestCase diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 469e81f34..1a279d6d7 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -1138,10 +1138,6 @@ class PlanetResource < JSONAPI::Resource has_one :planet_type has_many :tags, acts_as_set: true - - def records_for_moons(opts = {}) - Moon.joins(:craters).select('moons.*, craters.code').distinct - end end class PropertyResource < JSONAPI::Resource From d46a08092bfb29df1217a985438cf44c79a7817e Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Wed, 11 Jan 2017 14:36:24 -0500 Subject: [PATCH 10/60] Rework model_name in derived resources Fixes an issue where the recreated relationships might be using the wrong model_name if the model_name is changed in a resource that is derived from a non abstract resource, such as done in many of the tests. Breaking change: Derived resources now use the model name of their base resource, if it is not abstract. Cleans up the tests to not have the warnings about missing models. Fixes issue in _model_class related to #952, and renames @model (class level) to @model_class to avoid confusion with instance level @model Fixes #952, #654 (cherry picked from commit 280ccea) --- lib/jsonapi/resource.rb | 50 ++++++++++----- test/fixtures/active_record.rb | 1 + .../jsonapi_request/jsonapi_request_test.rb | 2 +- test/unit/resource/resource_test.rb | 62 +++++++++++-------- 4 files changed, 72 insertions(+), 43 deletions(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 58e930f82..1c0041b4c 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -416,18 +416,15 @@ def inherited(subclass) subclass.immutable(false) subclass.caching(false) subclass._attributes = (_attributes || {}).dup + subclass._model_hints = (_model_hints || {}).dup - subclass._relationships = {} - # Add the relationships from the base class to the subclass using the original options - if _relationships.is_a?(Hash) - _relationships.each_value do |relationship| - options = relationship.options.dup - options[:parent_resource] = subclass - subclass._add_relationship(relationship.class, relationship.name, options) - end + unless _model_name.empty? + subclass.model_name(_model_name, add_model_hint: (_model_hints && !_model_hints[_model_name].nil?) == true) end + subclass.rebuild_relationships(_relationships || {}) + subclass._allowed_filters = (_allowed_filters || Set.new).dup type = subclass.name.demodulize.sub(/Resource$/, '').underscore @@ -438,6 +435,20 @@ def inherited(subclass) check_reserved_resource_name(subclass._type, subclass.name) end + def rebuild_relationships(relationships) + original_relationships = relationships.deep_dup + + @_relationships = {} + + if original_relationships.is_a?(Hash) + original_relationships.each_value do |relationship| + options = relationship.options.dup + options[:parent_resource] = self + _add_relationship(relationship.class, relationship.name, options) + end + end + end + def resource_for(type) type = type.underscore type_with_module = type.include?('/') ? type : module_path + type @@ -554,6 +565,8 @@ def model_name(model, options = {}) @_model_name = model.to_sym model_hint(model: @_model_name, resource: self) unless options[:add_model_hint] == false + + rebuild_relationships(_relationships) end def model_hint(model: _model_name, resource: _type) @@ -900,10 +913,11 @@ def _model_name if _abstract return '' else - return @_model_name if defined?(@_model_name) + return @_model_name.to_s if defined?(@_model_name) class_name = self.name return '' if class_name.nil? - return @_model_name = class_name.demodulize.sub(/Resource$/, '') + @_model_name = class_name.demodulize.sub(/Resource$/, '') + return @_model_name.to_s end end @@ -974,11 +988,17 @@ def attribute_caching_context(context) def _model_class return nil if _abstract - return @model if defined?(@model) - return nil if self.name.to_s.blank? && _model_name.to_s.blank? - @model = _model_name.to_s.safe_constantize - warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." if @model.nil? - @model + return @model_class if @model_class + + model_name = _model_name + return nil if model_name.to_s.blank? + + @model_class = model_name.to_s.safe_constantize + if @model_class.nil? + warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." + end + + @model_class end def _allowed_filter?(filter) diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 1a279d6d7..878aab207 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -961,6 +961,7 @@ class CompanyResource < JSONAPI::Resource end class FirmResource < CompanyResource + model_name "Firm" end class TagResource < JSONAPI::Resource diff --git a/test/unit/jsonapi_request/jsonapi_request_test.rb b/test/unit/jsonapi_request/jsonapi_request_test.rb index b96ffb1d1..a4dbea09c 100644 --- a/test/unit/jsonapi_request/jsonapi_request_test.rb +++ b/test/unit/jsonapi_request/jsonapi_request_test.rb @@ -4,7 +4,7 @@ class CatResource < JSONAPI::Resource attribute :name attribute :breed - belongs_to :mother, class_name: 'Cat' + has_one :mother, class_name: 'Cat' has_one :father, class_name: 'Cat' filters :name diff --git a/test/unit/resource/resource_test.rb b/test/unit/resource/resource_test.rb index 4c8e94daa..83f9ab4c4 100644 --- a/test/unit/resource/resource_test.rb +++ b/test/unit/resource/resource_test.rb @@ -47,7 +47,9 @@ class NoMatchAbstractResource < JSONAPI::Resource abstract end -class CatResource < JSONAPI::Resource +class FelineResource < JSONAPI::Resource + model_name 'Cat' + attribute :name attribute :breed attribute :kind, :delegate => :breed @@ -98,6 +100,12 @@ class RelatedResource < MyModule::RelatedResource end end +class PostWithReadonlyAttributesResource < JSONAPI::Resource + model_name 'Post' + attribute :title, readonly: true + has_one :author, readonly: true +end + class ResourceTest < ActiveSupport::TestCase def setup @post = Post.first @@ -175,7 +183,7 @@ def test_derived_not_abstract def test_nil_model_class # ToDo:Figure out why this test does not work on Rails 4.0 # :nocov: - if Rails::VERSION::MAJOR >= 4 && Rails::VERSION::MINOR >= 1 + if (Rails::VERSION::MAJOR >= 4 && Rails::VERSION::MINOR >= 1) || (Rails::VERSION::MAJOR >= 5) assert_output nil, "[MODEL NOT FOUND] Model could not be found for NoMatchResource. If this a base Resource declare it as abstract.\n" do assert_nil NoMatchResource._model_class end @@ -194,13 +202,13 @@ def test_model_alternate end def test_class_attributes - attrs = CatResource._attributes + attrs = FelineResource._attributes assert_kind_of(Hash, attrs) assert_equal(attrs.keys.size, 4) end def test_class_relationships - relationships = CatResource._relationships + relationships = FelineResource._relationships assert_kind_of(Hash, relationships) assert_equal(relationships.size, 2) end @@ -214,16 +222,16 @@ def test_replace_polymorphic_to_one_link end def test_duplicate_relationship_name - assert_output nil, "[DUPLICATE RELATIONSHIP] `mother` has already been defined in CatResource.\n" do - CatResource.instance_eval do + assert_output nil, "[DUPLICATE RELATIONSHIP] `mother` has already been defined in FelineResource.\n" do + FelineResource.instance_eval do has_one :mother, class_name: 'Cat' end end end def test_duplicate_attribute_name - assert_output nil, "[DUPLICATE ATTRIBUTE] `name` has already been defined in CatResource.\n" do - CatResource.instance_eval do + assert_output nil, "[DUPLICATE ATTRIBUTE] `name` has already been defined in FelineResource.\n" do + FelineResource.instance_eval do attribute :name end end @@ -294,7 +302,7 @@ def test_find_by_key_with_customized_base_records end def test_updatable_fields_does_not_include_id - assert(!CatResource.updatable_fields.include?(:id)) + assert(!FelineResource.updatable_fields.include?(:id)) end def test_filter_on_to_many_relationship_id @@ -438,60 +446,60 @@ def apply_pagination(records, criteria, order_options) end def test_key_type_integer - CatResource.instance_eval do + FelineResource.instance_eval do key_type :integer end - assert CatResource.verify_key('45') - assert CatResource.verify_key(45) + assert FelineResource.verify_key('45') + assert FelineResource.verify_key(45) assert_raises JSONAPI::Exceptions::InvalidFieldValue do - CatResource.verify_key('45,345') + FelineResource.verify_key('45,345') end ensure - CatResource.instance_eval do + FelineResource.instance_eval do key_type nil end end def test_key_type_string - CatResource.instance_eval do + FelineResource.instance_eval do key_type :string end - assert CatResource.verify_key('45') - assert CatResource.verify_key(45) + assert FelineResource.verify_key('45') + assert FelineResource.verify_key(45) assert_raises JSONAPI::Exceptions::InvalidFieldValue do - CatResource.verify_key('45,345') + FelineResource.verify_key('45,345') end ensure - CatResource.instance_eval do + FelineResource.instance_eval do key_type nil end end def test_key_type_uuid - CatResource.instance_eval do + FelineResource.instance_eval do key_type :uuid end - assert CatResource.verify_key('f1a4d5f2-e77a-4d0a-acbb-ee0b98b3f6b5') + assert FelineResource.verify_key('f1a4d5f2-e77a-4d0a-acbb-ee0b98b3f6b5') assert_raises JSONAPI::Exceptions::InvalidFieldValue do - CatResource.verify_key('f1a-e77a-4d0a-acbb-ee0b98b3f6b5') + FelineResource.verify_key('f1a-e77a-4d0a-acbb-ee0b98b3f6b5') end ensure - CatResource.instance_eval do + FelineResource.instance_eval do key_type nil end end def test_key_type_proc - CatResource.instance_eval do + FelineResource.instance_eval do key_type -> (key, context) { return key if key.nil? if key.to_s.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/) @@ -502,14 +510,14 @@ def test_key_type_proc } end - assert CatResource.verify_key('f1a4d5f2-e77a-4d0a-acbb-ee0b98b3f6b5') + assert FelineResource.verify_key('f1a4d5f2-e77a-4d0a-acbb-ee0b98b3f6b5') assert_raises JSONAPI::Exceptions::InvalidFieldValue do - CatResource.verify_key('f1a-e77a-4d0a-acbb-ee0b98b3f6b5') + FelineResource.verify_key('f1a-e77a-4d0a-acbb-ee0b98b3f6b5') end ensure - CatResource.instance_eval do + FelineResource.instance_eval do key_type nil end end From de7e7d349c3a8849a49d7cdc27f5d7e80661598c Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Mon, 2 Jan 2017 11:29:40 -0500 Subject: [PATCH 11/60] Fix 628 CSV parsing errors (#937) * Added test and potential fix for #628. * Add handling for CSV parsing errors. (cherry picked from commit 9306ec0) --- lib/jsonapi/request_parser.rb | 31 ++++++++++++++++------- lib/jsonapi/resource.rb | 6 ++++- test/integration/requests/request_test.rb | 29 +++++++++++++++++++++ 3 files changed, 56 insertions(+), 10 deletions(-) diff --git a/lib/jsonapi/request_parser.rb b/lib/jsonapi/request_parser.rb index 2e0faacfa..09ce48712 100644 --- a/lib/jsonapi/request_parser.rb +++ b/lib/jsonapi/request_parser.rb @@ -210,23 +210,28 @@ def check_include(resource_klass, include_parts) end end - def parse_include_directives(include) - return if include.nil? + def parse_include_directives(raw_include) + return unless raw_include unless JSONAPI.configuration.allow_include fail JSONAPI::Exceptions::ParametersNotAllowed.new([:include]) end - included_resources = CSV.parse_line(include) - return if included_resources.nil? + included_resources = [] + begin + included_resources += CSV.parse_line(raw_include) + rescue CSV::MalformedCSVError + fail JSONAPI::Exceptions::InvalidInclude.new(format_key(@resource_klass._type), raw_include) + end + + return if included_resources.empty? - include = [] - included_resources.each do |included_resource| + result = included_resources.map do |included_resource| check_include(@resource_klass, included_resource.partition('.')) - include.push(unformat_key(included_resource).to_s) + unformat_key(included_resource).to_s end - @include_directives = JSONAPI::IncludeDirectives.new(@resource_klass, include) + @include_directives = JSONAPI::IncludeDirectives.new(@resource_klass, result) end def parse_filters(filters) @@ -265,7 +270,15 @@ def parse_sort_criteria(sort_criteria) fail JSONAPI::Exceptions::ParametersNotAllowed.new([:sort]) end - @sort_criteria = CSV.parse_line(URI.unescape(sort_criteria)).collect do |sort| + sorts = [] + begin + raw = URI.unescape(sort_criteria) + sorts += CSV.parse_line(raw) + rescue CSV::MalformedCSVError + fail JSONAPI::Exceptions::InvalidSortCriteria.new(format_key(@resource_klass._type), raw) + end + + @sort_criteria = sorts.collect do |sort| if sort.start_with?('-') sort_criteria = { field: unformat_key(sort[1..-1]).to_s } sort_criteria[:direction] = :desc diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 1c0041b4c..7d4a0bfa2 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -820,7 +820,11 @@ def is_filter_relationship?(filter) def verify_filter(filter, raw, context = nil) filter_values = [] if raw.present? - filter_values += raw.is_a?(String) ? CSV.parse_line(raw) : [raw] + begin + filter_values += raw.is_a?(String) ? CSV.parse_line(raw) : [raw] + rescue CSV::MalformedCSVError + filter_values << raw + end end strategy = _allowed_filters.fetch(filter, Hash.new)[:verify] diff --git a/test/integration/requests/request_test.rb b/test/integration/requests/request_test.rb index dc10b78e8..31821f8fd 100644 --- a/test/integration/requests/request_test.rb +++ b/test/integration/requests/request_test.rb @@ -45,6 +45,15 @@ def test_get_underscored_key JSONAPI.configuration = original_config end + def test_filter_with_value_containing_double_quote + original_config = JSONAPI.configuration.dup + JSONAPI.configuration.json_key_format = :underscored_key + get '/iso_currencies?filter[country_name]=%22' + assert_jsonapi_response 200 + ensure + JSONAPI.configuration = original_config + end + def test_get_underscored_key_filtered original_config = JSONAPI.configuration.dup JSONAPI.configuration.json_key_format = :underscored_key @@ -1063,6 +1072,26 @@ def test_sort_parameter_not_allowed JSONAPI.configuration.allow_sort = true end + def test_sort_parameter_quoted + get '/api/v2/books?sort=%22title%22', headers: { 'Accept' => JSONAPI::MEDIA_TYPE } + assert_jsonapi_response 200 + end + + def test_sort_parameter_openquoted + get '/api/v2/books?sort=%22title', headers: { 'Accept' => JSONAPI::MEDIA_TYPE } + assert_jsonapi_response 400 + end + + def test_include_parameter_quoted + get '/api/v2/posts?include=%22author%22', headers: { 'Accept' => JSONAPI::MEDIA_TYPE } + assert_jsonapi_response 200 + end + + def test_include_parameter_openquoted + get '/api/v2/posts?include=%22author', headers: { 'Accept' => JSONAPI::MEDIA_TYPE } + assert_jsonapi_response 400 + end + def test_getting_different_resources_when_sti assert_cacheable_jsonapi_get '/vehicles' types = json_response['data'].map{|r| r['type']}.sort From 423956120808b00e902ddeb82e999e2d53ac8004 Mon Sep 17 00:00:00 2001 From: Hugh Barrigan Date: Thu, 29 Dec 2016 17:00:08 -0500 Subject: [PATCH 12/60] Fix has_one polymorphism (#945) * Fix has_one polymorphism * Add tests for has one polymorphic serialization (cherry picked from commit 9ad4d91) --- lib/jsonapi/relationship_builder.rb | 12 ++- test/fixtures/active_record.rb | 77 +++++++++++++++ test/fixtures/answers.yml | 12 +++ test/fixtures/doctors.yml | 3 + test/fixtures/patients.yml | 3 + test/fixtures/questions.yml | 6 ++ test/test_helper.rb | 5 + .../serializer/polymorphic_serializer_test.rb | 97 ++++++++++++++++++- 8 files changed, 211 insertions(+), 4 deletions(-) create mode 100644 test/fixtures/answers.yml create mode 100644 test/fixtures/doctors.yml create mode 100644 test/fixtures/patients.yml create mode 100644 test/fixtures/questions.yml diff --git a/lib/jsonapi/relationship_builder.rb b/lib/jsonapi/relationship_builder.rb index c5774e6f4..9c7364d2f 100644 --- a/lib/jsonapi/relationship_builder.rb +++ b/lib/jsonapi/relationship_builder.rb @@ -120,10 +120,16 @@ def build_has_one(relationship, foreign_key, associated_records_method_name, rel define_on_resource relationship_name do |options = {}| relationship = self.class._relationships[relationship_name] - resource_klass = relationship.resource_klass - if resource_klass + if relationship.polymorphic? associated_model = public_send(associated_records_method_name) - return associated_model ? resource_klass.new(associated_model, @context) : nil + resource_klass = self.class.resource_for_model(associated_model) if associated_model + return resource_klass.new(associated_model, @context) if resource_klass && associated_model + else + resource_klass = relationship.resource_klass + if resource_klass + associated_model = public_send(associated_records_method_name) + return associated_model ? resource_klass.new(associated_model, @context) : nil + end end end end diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 878aab207..1a26bbf85 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -291,6 +291,25 @@ t.timestamps null: false end + create_table :questions, force: true do |t| + t.string :text + end + + create_table :answers, force: true do |t| + t.references :question + t.integer :respondent_id + t.string :respondent_type + t.string :text + end + + create_table :patients, force: true do |t| + t.string :name + end + + create_table :doctors, force: true do |t| + t.string :name + end + # special cases end @@ -606,6 +625,25 @@ class RelatedThing < ActiveRecord::Base belongs_to :to, class_name: Thing, foreign_key: :to_id end +class Question < ActiveRecord::Base + has_one :answer + + def respondent + answer.try(:respondent) + end +end + +class Answer < ActiveRecord::Base + belongs_to :question + belongs_to :respondent, polymorphic: true +end + +class Patient < ActiveRecord::Base +end + +class Doctor < ActiveRecord::Base +end + module Api module V7 class Client < Customer @@ -882,6 +920,21 @@ class BoxesController < JSONAPI::ResourceController end end +class QuestionsController < JSONAPI::ResourceController +end + +class AnswersController < JSONAPI::ResourceController +end + +class PatientsController < JSONAPI::ResourceController +end + +class DoctorsController < JSONAPI::ResourceController +end + +class RespondentController < JSONAPI::ResourceController +end + ### RESOURCES class BaseResource < JSONAPI::Resource abstract @@ -1796,6 +1849,30 @@ class UserResource < JSONAPI::Resource end end +class QuestionResource < JSONAPI::Resource + has_one :answer + has_one :respondent, polymorphic: true, class_name: "Respondent", foreign_key_on: :related + + attributes :text +end + +class AnswerResource < JSONAPI::Resource + has_one :question + has_one :respondent, polymorphic: true +end + +class PatientResource < JSONAPI::Resource + attributes :name +end + +class DoctorResource < JSONAPI::Resource + attributes :name +end + +class RespondentResource < JSONAPI::Resource + abstract +end + ### PORO Data - don't do this in a production app $breed_data = BreedData.new $breed_data.add(Breed.new(0, 'persian')) diff --git a/test/fixtures/answers.yml b/test/fixtures/answers.yml new file mode 100644 index 000000000..197d8d6a8 --- /dev/null +++ b/test/fixtures/answers.yml @@ -0,0 +1,12 @@ +answer1: + id: 1 + question_id: 1 + text: Great thanks + respondent_id: 1 + respondent_type: Patient +answer2: + id: 2 + question_id: 2 + text: Better than last week + respondent_id: 1 + respondent_type: Doctor \ No newline at end of file diff --git a/test/fixtures/doctors.yml b/test/fixtures/doctors.yml new file mode 100644 index 000000000..c9a53c919 --- /dev/null +++ b/test/fixtures/doctors.yml @@ -0,0 +1,3 @@ +doctor1: + id: 1 + name: Henry Jones Jr \ No newline at end of file diff --git a/test/fixtures/patients.yml b/test/fixtures/patients.yml new file mode 100644 index 000000000..a75987574 --- /dev/null +++ b/test/fixtures/patients.yml @@ -0,0 +1,3 @@ +patient1: + id: 1 + name: Bob Smith \ No newline at end of file diff --git a/test/fixtures/questions.yml b/test/fixtures/questions.yml new file mode 100644 index 000000000..caabed013 --- /dev/null +++ b/test/fixtures/questions.yml @@ -0,0 +1,6 @@ +question1: + id: 1 + text: How are you feeling today? +question2: + id: 2 + text: How does the patient look today? \ No newline at end of file diff --git a/test/test_helper.rb b/test/test_helper.rb index 9ce9a60af..51ba0459d 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -255,6 +255,11 @@ class CatResource < JSONAPI::Resource jsonapi_resources :books jsonapi_resources :authors + jsonapi_resources :questions + jsonapi_resources :answers + jsonapi_resources :doctors + jsonapi_resources :patients + namespace :api do jsonapi_resources :boxes diff --git a/test/unit/serializer/polymorphic_serializer_test.rb b/test/unit/serializer/polymorphic_serializer_test.rb index 347fc8d33..bb905fde8 100644 --- a/test/unit/serializer/polymorphic_serializer_test.rb +++ b/test/unit/serializer/polymorphic_serializer_test.rb @@ -7,6 +7,8 @@ def setup @pictures = Picture.all @person = Person.find(1) + @questions = Question.all + JSONAPI.configuration.json_key_format = :camelized_key JSONAPI.configuration.route_format = :camelized_route end @@ -128,7 +130,7 @@ def test_sti_polymorphic_to_many_serialization ) end - def test_polymorphic_to_one_serialization + def test_polymorphic_belongs_to_serialization serialized_data = JSONAPI::ResourceSerializer.new( PictureResource, include: %w(imageable) @@ -249,6 +251,99 @@ def test_polymorphic_to_one_serialization ) end + def test_polymorphic_has_one_serialization + serialized_data = JSONAPI::ResourceSerializer.new( + QuestionResource, + include: %w(respondent) + ).serialize_to_hash(@questions.map { |p| QuestionResource.new p, nil }) + + assert_hash_equals( + { + data: [ + { + id: '1', + type: 'questions', + links: { + self: '/questions/1' + }, + attributes: { + text: 'How are you feeling today?' + }, + relationships: { + answer: { + links: { + self: '/questions/1/relationships/answer', + related: '/questions/1/answer' + } + }, + respondent: { + links: { + self: '/questions/1/relationships/respondent', + related: '/questions/1/respondent' + }, + data: { + type: 'patients', + id: '1' + } + } + } + }, + { + id: '2', + type: 'questions', + links: { + self: '/questions/2' + }, + attributes: { + text: 'How does the patient look today?' + }, + relationships: { + answer: { + links: { + self: '/questions/2/relationships/answer', + related: '/questions/2/answer' + } + }, + respondent: { + links: { + self: '/questions/2/relationships/respondent', + related: '/questions/2/respondent' + }, + data: { + type: 'doctors', + id: '1' + } + } + } + } + ], + :included => [ + { + id: '1', + type: 'patients', + links: { + self: '/patients/1' + }, + attributes: { + name: 'Bob Smith' + }, + }, + { + id: '1', + type: 'doctors', + links: { + self: '/doctors/1' + }, + attributes: { + name: 'Henry Jones Jr' + }, + } + ] + }, + serialized_data + ) + end + def test_polymorphic_get_related_resource get '/pictures/1/imageable', headers: { 'Accept' => JSONAPI::MEDIA_TYPE } serialized_data = JSON.parse(response.body) From a5b06b66a95e263b1065c59fdba67a40c7b04d33 Mon Sep 17 00:00:00 2001 From: Greg Fisher Date: Tue, 13 Dec 2016 08:28:08 -0500 Subject: [PATCH 13/60] Catch LoadError when checkin for engine (cherry picked from commit 31d22d1) --- lib/jsonapi/link_builder.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/jsonapi/link_builder.rb b/lib/jsonapi/link_builder.rb index 1799152fc..61604496c 100644 --- a/lib/jsonapi/link_builder.rb +++ b/lib/jsonapi/link_builder.rb @@ -57,8 +57,12 @@ def self_link(source) def build_engine_name scopes = module_scopes_from_class(primary_resource_klass) - unless scopes.empty? - "#{ scopes.first.to_s.camelize }::Engine".safe_constantize + begin + unless scopes.empty? + "#{ scopes.first.to_s.camelize }::Engine".safe_constantize + end + rescue LoadError => e + nil end end From 1df2b3b0cfe39892fb7a58142b886c07f544e54d Mon Sep 17 00:00:00 2001 From: David Simon Date: Mon, 28 Nov 2016 12:15:55 -0500 Subject: [PATCH 14/60] Skip preloading of polymorphic relations, better handling of serialization with partially preloaded relations, resolves #889 (cherry picked from commit d9d9d3f) --- test/controllers/controller_test.rb | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index adea95ea4..c8e05a18d 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -1972,6 +1972,36 @@ def test_documents_index_with_polymorphic_include_one_level end end +class PicturesControllerTest < ActionController::TestCase + def test_pictures_index + assert_cacheable_get :index + assert_response :success + assert_equal 3, json_response['data'].size + end + + def test_pictures_index_with_polymorphic_include_one_level + assert_cacheable_get :index, params: {include: 'imageable'} + assert_response :success + assert_equal 3, json_response['data'].size + assert_equal 2, json_response['included'].size + end +end + +class DocumentsControllerTest < ActionController::TestCase + def test_documents_index + assert_cacheable_get :index + assert_response :success + assert_equal 1, json_response['data'].size + end + + def test_documents_index_with_polymorphic_include_one_level + assert_cacheable_get :index, params: {include: 'pictures'} + assert_response :success + assert_equal 1, json_response['data'].size + assert_equal 1, json_response['included'].size + end +end + class ExpenseEntriesControllerTest < ActionController::TestCase def setup JSONAPI.configuration.json_key_format = :camelized_key From fd535b33541e6cdb55c6839d15b804dc0b180198 Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Tue, 17 Jan 2017 11:31:28 -0500 Subject: [PATCH 15/60] Bump to 0.9.0.beta2 --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 3378dd89e..60d17de6b 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.9.0.beta1' + VERSION = '0.9.0.beta2' end end From c05881625140dfad0b6157f8937a7dfe18152d76 Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Thu, 19 Jan 2017 11:54:33 -0500 Subject: [PATCH 16/60] Default `id` to being a read only (not creatable) attribute Fixes #960 Potentially a breaking change for apps with guids (cherry picked from commit 4f51331) --- lib/jsonapi/resource.rb | 6 ++++-- test/fixtures/active_record.rb | 6 +++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 7d4a0bfa2..f268dc133 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -430,7 +430,9 @@ def inherited(subclass) type = subclass.name.demodulize.sub(/Resource$/, '').underscore subclass._type = type.pluralize.to_sym - subclass.attribute :id, format: :id + unless subclass._attributes[:id] + subclass.attribute :id, format: :id + end check_reserved_resource_name(subclass._type, subclass.name) end @@ -598,7 +600,7 @@ def updatable_fields(_context = nil) # Override in your resource to filter the creatable keys def creatable_fields(_context = nil) - _updatable_relationships | _attributes.keys + _updatable_relationships | _attributes.keys - [:id] end # Override in your resource to filter the sortable keys diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 1a26bbf85..b5c11d72d 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -1120,7 +1120,7 @@ def self.updatable_fields(context) end def self.creatable_fields(context) - super(context) - [:subject, :id] + super(context) - [:subject] end def self.sortable_fields(context) @@ -1142,6 +1142,10 @@ class HairCutResource < JSONAPI::Resource class IsoCurrencyResource < JSONAPI::Resource attributes :name, :country_name, :minor_unit + def self.creatable_fields(_context = nil) + super + [:id] + end + filter :country_name key_type :string From 66531b312c834518c8d4f8794d94961a7d467000 Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Thu, 19 Jan 2017 12:50:41 -0500 Subject: [PATCH 17/60] Bump to 0.9.0.beta3 --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 60d17de6b..3be3a5aa8 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.9.0.beta2' + VERSION = '0.9.0.beta3' end end From cc89e042ee2301804a95168714b5152b4c6c07e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Scott=20Gonz=C3=A1lez?= Date: Mon, 30 Jan 2017 21:29:08 -0500 Subject: [PATCH 18/60] Fix wording for missing model (cherry picked from commit 57fa0ae) --- lib/jsonapi/resource.rb | 2 +- test/unit/resource/resource_test.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index f268dc133..7eefcbee5 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -1001,7 +1001,7 @@ def _model_class @model_class = model_name.to_s.safe_constantize if @model_class.nil? - warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this a base Resource declare it as abstract." + warn "[MODEL NOT FOUND] Model could not be found for #{self.name}. If this is a base Resource declare it as abstract." end @model_class diff --git a/test/unit/resource/resource_test.rb b/test/unit/resource/resource_test.rb index 83f9ab4c4..83c417c61 100644 --- a/test/unit/resource/resource_test.rb +++ b/test/unit/resource/resource_test.rb @@ -184,7 +184,7 @@ def test_nil_model_class # ToDo:Figure out why this test does not work on Rails 4.0 # :nocov: if (Rails::VERSION::MAJOR >= 4 && Rails::VERSION::MINOR >= 1) || (Rails::VERSION::MAJOR >= 5) - assert_output nil, "[MODEL NOT FOUND] Model could not be found for NoMatchResource. If this a base Resource declare it as abstract.\n" do + assert_output nil, "[MODEL NOT FOUND] Model could not be found for NoMatchResource. If this is a base Resource declare it as abstract.\n" do assert_nil NoMatchResource._model_class end end @@ -593,7 +593,7 @@ class NoModelResource < JSONAPI::Resource NoModelResource._model_class CODE end - assert_match "[MODEL NOT FOUND] Model could not be found for ResourceTest::NoModelResource. If this a base Resource declare it as abstract.\n", err + assert_match "[MODEL NOT FOUND] Model could not be found for ResourceTest::NoModelResource. If this is a base Resource declare it as abstract.\n", err end def test_no_warning_when_abstract From e8ad5a262b9793fe6b537e62acad97c30a152f2e Mon Sep 17 00:00:00 2001 From: Ben Date: Sun, 22 Jan 2017 01:05:01 -0500 Subject: [PATCH 19/60] fix page count when paginator is none (cherry picked from commit 48eaa02) --- lib/jsonapi/processor.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/processor.rb b/lib/jsonapi/processor.rb index 82566568a..7cb527ed7 100644 --- a/lib/jsonapi/processor.rb +++ b/lib/jsonapi/processor.rb @@ -96,7 +96,7 @@ def find end if (JSONAPI.configuration.top_level_meta_include_page_count && page_options[:record_count]) - page_options[:page_count] = paginator.calculate_page_count(page_options[:record_count]) + page_options[:page_count] = paginator ? paginator.calculate_page_count(page_options[:record_count]) : 1 end if JSONAPI.configuration.top_level_links_include_pagination && paginator From 68452127eccb966338c126a15a3b8fb2dec1548e Mon Sep 17 00:00:00 2001 From: Benjamin Fleischer Date: Sun, 5 Feb 2017 21:09:26 -0500 Subject: [PATCH 20/60] Fix typos ``` go get -u github.com/client9/misspell/cmd/misspell misspell -w -error -source=text . ``` (cherry picked from commit 726b102) --- lib/jsonapi/resource.rb | 2 +- test/controllers/controller_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index 7eefcbee5..efaae4635 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -656,7 +656,7 @@ def apply_sort(records, order_options, _context = {}) associations = _lookup_association_chain([records.model.to_s, *model_names]) joins_query = _build_joins([records.model, *associations]) - # _sorting is appended to avoid name clashes with manual joins eg. overriden filters + # _sorting is appended to avoid name clashes with manual joins eg. overridden filters order_by_query = "#{associations.last.name}_sorting.#{column_name} #{direction}" records = records.joins(joins_query).order(order_by_query) else diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index c8e05a18d..2d74a2387 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -2518,7 +2518,7 @@ def test_destroy_relationship_has_and_belongs_to_many JSONAPI.configuration.use_relationship_reflection = false end - def test_destroy_relationship_has_and_belongs_to_many_refect + def test_destroy_relationship_has_and_belongs_to_many_reflect JSONAPI.configuration.use_relationship_reflection = true assert_equal 2, Book.find(2).authors.count From 144d487e9c87bc43b5be4dd8de8b2915ac9fb573 Mon Sep 17 00:00:00 2001 From: Hidde-Jan Jongsma Date: Tue, 7 Feb 2017 06:18:39 -0500 Subject: [PATCH 21/60] Filter nil values from include param (cherry picked from commit 4b93707) --- lib/jsonapi/request_parser.rb | 2 +- test/controllers/controller_test.rb | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/request_parser.rb b/lib/jsonapi/request_parser.rb index 09ce48712..c7e0d6efa 100644 --- a/lib/jsonapi/request_parser.rb +++ b/lib/jsonapi/request_parser.rb @@ -226,7 +226,7 @@ def parse_include_directives(raw_include) return if included_resources.empty? - result = included_resources.map do |included_resource| + result = included_resources.compact.map do |included_resource| check_include(@resource_klass, included_resource.partition('.')) unformat_key(included_resource).to_s end diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index 2d74a2387..7bdf19c2d 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -3642,6 +3642,11 @@ def test_complex_includes_base assert_response :success end + def test_complex_includes_filters_nil_includes + assert_cacheable_get :index, params: {include: ',,'} + assert_response :success + end + def test_complex_includes_two_level assert_cacheable_get :index, params: {include: 'things,things.user'} From 5af1f17068b66b0a17b7b69e5db334c640f6f34b Mon Sep 17 00:00:00 2001 From: Larry Gebhardt Date: Tue, 14 Feb 2017 10:54:47 -0500 Subject: [PATCH 22/60] Bump to 0.9.0 --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 3be3a5aa8..3b1edaa47 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.9.0.beta3' + VERSION = '0.9.0' end end From be2fb43f5f8da2e632fb5f48200928b2dd3d8bf9 Mon Sep 17 00:00:00 2001 From: Dasun Pubudumal Date: Fri, 16 Feb 2024 16:44:09 +0000 Subject: [PATCH 23/60] Removing ForcedSSL line --- lib/jsonapi/resource_controller_metal.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/jsonapi/resource_controller_metal.rb b/lib/jsonapi/resource_controller_metal.rb index bf5bc9410..bb67d04a2 100644 --- a/lib/jsonapi/resource_controller_metal.rb +++ b/lib/jsonapi/resource_controller_metal.rb @@ -5,7 +5,6 @@ class ResourceControllerMetal < ActionController::Metal ActionController::Rendering, ActionController::Renderers::All, ActionController::StrongParameters, - ActionController::ForceSSL, ActionController::Instrumentation, JSONAPI::ActsAsResourceController ].freeze From 93ce889f21abe8e5ad6a376461ed74520bd356f1 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Thu, 12 Jun 2025 13:26:55 +0100 Subject: [PATCH 24/60] update (gemspec): change gemspec name to sanger-jsonapi-resources and update description for clarity --- jsonapi-resources.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 3f031d173..ec5ae2ccd 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -4,12 +4,12 @@ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jsonapi/resources/version' Gem::Specification.new do |spec| - spec.name = 'jsonapi-resources' + spec.name = 'sanger-jsonapi-resources' spec.version = JSONAPI::Resources::VERSION spec.authors = ['Dan Gebhardt', 'Larry Gebhardt'] spec.email = ['dan@cerebris.com', 'larry@cerebris.com'] spec.summary = 'Easily support JSON API in Rails.' - spec.description = 'A resource-centric approach to implementing the controllers, routes, and serializers needed to support the JSON API spec.' + spec.description = 'Forked from jsonapi-resources. A resource-centric approach to implementing the controllers, routes, and serializers needed to support the JSON API spec.' spec.homepage = 'https://github.com/cerebris/jsonapi-resources' spec.license = 'MIT' From f04adafb314f662f308f318db965cf1c008bdadc Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Thu, 12 Jun 2025 13:27:34 +0100 Subject: [PATCH 25/60] feature(sanger-jsonapi-resources): Add wrapper file for sanger-jsonapi-resources gem to ensure compatibility with RubyGems and Bundler --- lib/sanger-jsonapi-resources.rb | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 lib/sanger-jsonapi-resources.rb diff --git a/lib/sanger-jsonapi-resources.rb b/lib/sanger-jsonapi-resources.rb new file mode 100644 index 000000000..2b4763cf6 --- /dev/null +++ b/lib/sanger-jsonapi-resources.rb @@ -0,0 +1,7 @@ +# As we are packaging 'sanger-jsonapi-resources' as a separate gem, RubyGems expects +# the main file to be 'lib/sanger-jsonapi-resources.rb' to match the gem name. +# Without this file, requiring the gem or Rails autoloading would fail, even if the internal code is unchanged. +# This file exists to ensure compatibility with RubyGems and Bundler. +# The easiest solution is to use this wrapper file, which simply requires the original 'jsonapi-resources' code, +# so all internal references and modules remain unchanged and compatible. +require_relative 'jsonapi-resources' From 576455c093c4a22502e8d05a8d4a0b18aed8af53 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Thu, 12 Jun 2025 13:28:33 +0100 Subject: [PATCH 26/60] Change version number to 0.1.1 in version.rb (0.1.0 was published already) --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 3b1edaa47..86e2bcf31 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.9.0' + VERSION = '0.1.1' end end From 3f76a4628065bc81f6b75d276a83cc5e79ade329 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Thu, 12 Jun 2025 13:28:43 +0100 Subject: [PATCH 27/60] update README: change gem installation instructions to use sanger-jsonapi-resources --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c494c9c74..54df000ba 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ which *should* be compatible with JSON:API compliant server implementations such Add JR to your application's `Gemfile`: - gem 'jsonapi-resources' + gem 'sanger-jsonapi-resources' And then execute: @@ -36,7 +36,7 @@ And then execute: Or install it yourself as: - $ gem install jsonapi-resources + $ gem install sanger-jsonapi-resources **For further usage see the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/)** From 5174ea6f2ea912b41c0239f847fe0c36313deaab Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:28:25 +0100 Subject: [PATCH 28/60] update Gemfile: upgrade sqlite3 to version >= 1.4 and railties to ~> 7.1.0 which are required for compatibility with Rails 7.1 and Ruby 3.x --- Gemfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index c58d1c896..805949eb6 100644 --- a/Gemfile +++ b/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec platforms :ruby do - gem 'sqlite3', '1.3.10' + gem 'sqlite3', '>= 1.4' end platforms :jruby do @@ -17,7 +17,7 @@ when 'master' gem 'railties', { git: 'https://github.com/rails/rails.git' } gem 'arel', { git: 'https://github.com/rails/arel.git' } when 'default' - gem 'railties', '>= 5.0' + gem 'railties', '~> 7.1.0' else gem 'railties', "~> #{version}" end From c8bd96a65d26af789399b3f8764033a132eb96aa Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:31:58 +0100 Subject: [PATCH 29/60] update (gemspec): modify bundler dependency to allow versions >= 1.5 and < 3.0 (ensuring compatibility with both older and newer Ruby/Rails setups, while avoiding breaking changes introduced in Bundler 3.x.) ; add runtime dependency for csv (because Ruby 3.4+ no longer includes the csv library by default) --- jsonapi-resources.gemspec | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index ec5ae2ccd..59c135e3e 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -19,7 +19,7 @@ Gem::Specification.new do |spec| spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.1' - spec.add_development_dependency 'bundler', '~> 1.5' + spec.add_development_dependency 'bundler', '>= 1.5', '< 3.0' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest' spec.add_development_dependency 'minitest-spec-rails' @@ -29,4 +29,5 @@ Gem::Specification.new do |spec| spec.add_dependency 'activerecord', '>= 4.1' spec.add_dependency 'railties', '>= 4.1' spec.add_dependency 'concurrent-ruby' + spec.add_runtime_dependency 'csv' end From a7e0701bf8ac7f310050d36b9a0ae66f92899b4e Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:36:16 +0100 Subject: [PATCH 30/60] refactor(test_helper): remove redundant require and update fixture path handling --- test/test_helper.rb | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/test_helper.rb b/test/test_helper.rb index 51ba0459d..206fe8bd6 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -19,7 +19,6 @@ end require 'active_record/railtie' -require 'rails/test_help' require 'minitest/mock' require 'jsonapi-resources' require 'pry' @@ -38,7 +37,6 @@ config.json_key_format = :camelized_key end -puts "Testing With RAILS VERSION #{Rails.version}" class TestApp < Rails::Application config.eager_load = false @@ -203,9 +201,14 @@ def show_queries end end +# Establish the connection before loading schema +ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") + + TestApp.initialize! +# ✅ Now load the schema AFTER the connection is ready +require_relative 'fixtures/active_record' -require File.expand_path('../fixtures/active_record', __FILE__) module Pets module V1 @@ -417,12 +420,12 @@ def run_in_transaction? true end - self.fixture_path = "#{Rails.root}/fixtures" + self.fixture_paths = ["#{Rails.root}/fixtures"] fixtures :all end class ActiveSupport::TestCase - self.fixture_path = "#{Rails.root}/fixtures" + self.fixture_paths = ["#{Rails.root}/fixtures"] fixtures :all setup do @routes = TestApp.routes @@ -430,7 +433,7 @@ class ActiveSupport::TestCase end class ActionDispatch::IntegrationTest - self.fixture_path = "#{Rails.root}/fixtures" + self.fixture_paths = ["#{Rails.root}/fixtures"] fixtures :all def assert_jsonapi_response(expected_status, msg = nil) From 829502535ae78fdd66dcd96411fee47dff5fe8f9 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:36:36 +0100 Subject: [PATCH 31/60] fix(generators): add missing require statement for rails/generators in controller and resource generators --- lib/generators/jsonapi/controller_generator.rb | 1 + lib/generators/jsonapi/resource_generator.rb | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/generators/jsonapi/controller_generator.rb b/lib/generators/jsonapi/controller_generator.rb index 41ee4eb1e..d6aba8bf9 100644 --- a/lib/generators/jsonapi/controller_generator.rb +++ b/lib/generators/jsonapi/controller_generator.rb @@ -1,3 +1,4 @@ +require 'rails/generators' module Jsonapi class ControllerGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) diff --git a/lib/generators/jsonapi/resource_generator.rb b/lib/generators/jsonapi/resource_generator.rb index 80aa24b4d..25feb14a1 100644 --- a/lib/generators/jsonapi/resource_generator.rb +++ b/lib/generators/jsonapi/resource_generator.rb @@ -1,3 +1,4 @@ +require 'rails/generators' module Jsonapi class ResourceGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) From 3437f45265f031564933921c5aa2d21810e04616 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:42:22 +0100 Subject: [PATCH 32/60] fix(schema): Update schema definitions to use syntax compatible with recent Rails versions, replacing deprecated or invalid patterns to ensure proper table and index creation. --- test/fixtures/active_record.rb | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index b5c11d72d..9a958fa2e 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -57,18 +57,23 @@ t.timestamps null: false end - create_table :posts_tags, force: true do |t| - t.references :post, :tag, index: true + + + create_table :posts_tags, force: true, id: false do |t| + t.references :post, null: false + t.references :tag, null: false end add_index :posts_tags, [:post_id, :tag_id], unique: true create_table :special_post_tags, force: true do |t| - t.references :post, :tag, index: true + t.references :post, null: false, foreign_key: false + t.references :tag, null: false, foreign_key: false end add_index :special_post_tags, [:post_id, :tag_id], unique: true create_table :comments_tags, force: true do |t| - t.references :comment, :tag, index: true + t.references :comment, null: false + t.references :tag, null: false end create_table :iso_currencies, id: false, force: true do |t| @@ -95,7 +100,8 @@ end create_table :planets_tags, force: true do |t| - t.references :planet, :tag, index: true + t.references :planet, null: false + t.references :tag, null: false end add_index :planets_tags, [:planet_id, :tag_id], unique: true @@ -184,7 +190,8 @@ end create_table :purchase_orders_order_flags, force: true do |t| - t.references :purchase_order, :order_flag, index: true + t.references :purchase_order, null: false + t.references :order_flag, null: false end add_index :purchase_orders_order_flags, [:purchase_order_id, :order_flag_id], unique: true, name: "po_flags_idx" @@ -285,8 +292,8 @@ create_table :related_things, force: true do |t| t.string :name - t.references :from, references: :thing - t.references :to, references: :thing + t.references :from + t.references :to t.timestamps null: false end @@ -342,8 +349,8 @@ class Post < ActiveRecord::Base belongs_to :writer, class_name: 'Person', foreign_key: 'author_id' has_many :comments has_and_belongs_to_many :tags, join_table: :posts_tags - has_many :special_post_tags, source: :tag - has_many :special_tags, through: :special_post_tags, source: :tag + has_many :special_post_tags + has_many :special_tags, through: :special_post_tags belongs_to :section has_one :parent_post, class_name: 'Post', foreign_key: 'parent_post_id' @@ -621,8 +628,8 @@ class Thing < ActiveRecord::Base end class RelatedThing < ActiveRecord::Base - belongs_to :from, class_name: Thing, foreign_key: :from_id - belongs_to :to, class_name: Thing, foreign_key: :to_id + belongs_to :from, class_name: 'Thing', foreign_key: :from_id + belongs_to :to, class_name: 'Thing', foreign_key: :to_id end class Question < ActiveRecord::Base From 1c3bb37c39f7bf78428335ceda40b220e0b54a8e Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Tue, 17 Jun 2025 10:50:13 +0100 Subject: [PATCH 33/60] feat(ci): Add GitHub Actions configuration for continuous integration with Ruby and Rails testing --- .github/dependabot.yml | 10 ++++++++++ .github/workflows/ruby.yml | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ruby.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..573705517 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +# Set update schedule for GitHub Actions + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + # Check for updates to GitHub Actions every weekday + interval: "daily" diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml new file mode 100644 index 000000000..60f056246 --- /dev/null +++ b/.github/workflows/ruby.yml @@ -0,0 +1,35 @@ +name: CI + +on: + push: + branches: [ 'develop' ] + pull_request: + branches: ['**'] + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby: + - '3.3' + - '3.2' + rails: + - '7.1' + - '7.2' + database_url: + - sqlite3:test_db + env: + RAILS_VERSION: ${{ matrix.rails }} + DATABASE_URL: ${{ matrix.database_url }} + name: Ruby ${{ matrix.ruby }} Rails ${{ matrix.rails }} DB ${{ matrix.database_url }} + steps: + - uses: actions/checkout@v3 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run tests + run: bundle exec rake test From 3a64ede4143be342b22aabe1d9823cb74f6b2d13 Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Tue, 17 Jun 2025 11:43:07 +0100 Subject: [PATCH 34/60] fix(gemspec): Update authors and homepage to reflect current project ownership and repository link --- jsonapi-resources.gemspec | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 59c135e3e..9942ddf9e 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -6,11 +6,11 @@ require 'jsonapi/resources/version' Gem::Specification.new do |spec| spec.name = 'sanger-jsonapi-resources' spec.version = JSONAPI::Resources::VERSION - spec.authors = ['Dan Gebhardt', 'Larry Gebhardt'] - spec.email = ['dan@cerebris.com', 'larry@cerebris.com'] + spec.authors = ['PSD Team - Wellcome Trust Sanger Institute'] + spec.email = ['psd@sanger.ac.uk'] spec.summary = 'Easily support JSON API in Rails.' spec.description = 'Forked from jsonapi-resources. A resource-centric approach to implementing the controllers, routes, and serializers needed to support the JSON API spec.' - spec.homepage = 'https://github.com/cerebris/jsonapi-resources' + spec.homepage = 'https://github.com/sanger/jsonapi-resources' spec.license = 'MIT' spec.files = Dir.glob("{bin,lib}/**/*") + %w(LICENSE.txt README.md) From f52036b01b244e2739455a485a5c99d9991acf58 Mon Sep 17 00:00:00 2001 From: yoldas Date: Tue, 16 Sep 2025 23:57:56 +0100 Subject: [PATCH 35/60] Add compatibility for obsolete Rack status symbols --- lib/jsonapi/error.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/error.rb b/lib/jsonapi/error.rb index 41545c13e..fc39d93aa 100644 --- a/lib/jsonapi/error.rb +++ b/lib/jsonapi/error.rb @@ -15,7 +15,7 @@ def initialize(options = {}) @source = options[:source] @links = options[:links] - @status = Rack::Utils::SYMBOL_TO_STATUS_CODE[options[:status]].to_s + @status = Rack::Utils.status_code(options[:status]).to_s @meta = options[:meta] end From 21092b05ff00155878c55edca7971a87028dbb7c Mon Sep 17 00:00:00 2001 From: yoldas Date: Wed, 17 Sep 2025 00:37:26 +0100 Subject: [PATCH 36/60] Change version to 0.1.2 --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 86e2bcf31..07ba6bd5f 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.1.1' + VERSION = '0.1.2' end end From 24301c5af8eb520f1a5bc23cf922973112445fd0 Mon Sep 17 00:00:00 2001 From: Tom Whiteley Date: Wed, 1 Apr 2026 11:04:28 +0100 Subject: [PATCH 37/60] Updating CONTRIBUTING.md and README.md prior to merge into develop --- CONTRIBUTING.md | 30 ++++++++++++++++++++++++++++++ README.md | 29 +++++++++++++++-------------- 2 files changed, 45 insertions(+), 14 deletions(-) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..03ce14d91 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,30 @@ +# Contributing + +All contributions to this project are subject to the [MIT License](https://foss-haas.mit-license.org/). By submitting a contribution, you agree to license your work under these terms. + +## Contribution Process + +### 1. Issue First + +All contributions from outside the core team require an **Issue First** approach. Before submitting a pull request (PR), you must: + +- Open an issue in the repository. +- Ensure the issue includes: + - **Clear problem statement:** Describe the issue or feature request. + - **Reproduction steps:** If reporting a bug, provide steps to reproduce it. + - **Proposed approach:** Outline your suggested solution or implementation. + - **Why this change matters:** Explain the impact or necessity of the change. +- Tag `@sanger/psd-developers` in the issue to bring it to the attention of a maintainer. +- Wait for the issue to be assigned or approved by a maintainer. + +### 2. Pull Request + +Once your issue is approved: + +- Fork the repository and create a branch for your changes. +- Submit a PR referencing the approved issue. +- Ensure your code adheres to the project's coding standards and passes all tests. + +### 3. Review + +Maintainers will review your PR. Address any feedback before merging. \ No newline at end of file diff --git a/README.md b/README.md index 54df000ba..b7f2f18f2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=beta)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources) +# JSONAPI::Resources [![Gem Version](https://badge.fury.io/rb/jsonapi-resources.svg)](https://badge.fury.io/rb/jsonapi-resources) [![Build Status](https://secure.travis-ci.org/cerebris/jsonapi-resources.svg?branch=master)](http://travis-ci.org/cerebris/jsonapi-resources) [![Code Climate](https://codeclimate.com/github/cerebris/jsonapi-resources/badges/gpa.svg)](https://codeclimate.com/github/cerebris/jsonapi-resources) [![Join the chat at https://gitter.im/cerebris/jsonapi-resources](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/cerebris/jsonapi-resources?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -8,12 +8,12 @@ Like JSON:API itself, JR's design is focused on the resources served by an API. JR needs little more than a definition of your resources, including their attributes and relationships, to make your server compliant with JSON API. -JR is designed to work with Rails 4.2+, and provides custom routes, controllers, and serializers. JR's resources may be +JR is designed to work with Rails 5.1+, and provides custom routes, controllers, and serializers. JR's resources may be backed by ActiveRecord models or by custom objects. ## Documentation -Full documentation can be found at [http://jsonapi-resources.com](http://jsonapi-resources.com), including the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/) specific to this version. +Full documentation can be found at [http://jsonapi-resources.com](http://jsonapi-resources.com), including the [v0.10 alpha Guide](http://jsonapi-resources.com/v0.10/guide/) specific to this version. ## Demo App @@ -28,26 +28,27 @@ which *should* be compatible with JSON:API compliant server implementations such Add JR to your application's `Gemfile`: - gem 'sanger-jsonapi-resources' +``` +gem 'jsonapi-resources' +``` And then execute: - $ bundle +```bash +bundle +``` Or install it yourself as: - $ gem install sanger-jsonapi-resources +```bash +gem install jsonapi-resources +``` -**For further usage see the [v0.9 beta Guide](http://jsonapi-resources.com/v0.9/guide/)** +**For further usage see the [v0.10 alpha Guide](http://jsonapi-resources.com/v0.10/guide/)** ## Contributing - -1. Fork it ( http://github.com/cerebris/jsonapi-resources/fork ) -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create a new Pull Request +See CONTRIBUTING.md for details. ## License -Copyright 2014-2016 Cerebris Corporation. MIT License (see LICENSE for details). +Copyright 2014-2021 Cerebris Corporation. MIT License (see LICENSE for details). From 7745ac375d1c8e96a24564e350a176291f6cdb23 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Fri, 3 Jul 2026 13:16:48 +0100 Subject: [PATCH 38/60] ci: add latest versions to ci --- .github/workflows/ruby.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index 60f056246..5cc998fae 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -13,11 +13,13 @@ jobs: fail-fast: false matrix: ruby: - - '3.3' - '3.2' + - '3.3' + - '3.4' rails: - '7.1' - '7.2' + - '8.0' database_url: - sqlite3:test_db env: @@ -25,7 +27,7 @@ jobs: DATABASE_URL: ${{ matrix.database_url }} name: Ruby ${{ matrix.ruby }} Rails ${{ matrix.rails }} DB ${{ matrix.database_url }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: From b625b34ba2b8ac31d3816a01126b0fa06d069ccf Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Fri, 3 Jul 2026 13:26:58 +0100 Subject: [PATCH 39/60] test: repair deprecation warning --- test/test_helper.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/test_helper.rb b/test/test_helper.rb index 206fe8bd6..dd956e077 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -56,6 +56,11 @@ class TestApp < Rails::Application config.active_record.time_zone_aware_types = [:time, :datetime] config.active_record.belongs_to_required_by_default = false end + + # Use a modern cache serialization format to avoid Rails 7.2+ deprecations. + if Rails::VERSION::MAJOR >= 7 && config.active_support.respond_to?(:cache_format_version=) + config.active_support.cache_format_version = 7.1 + end end module MyEngine From cc3678d4e1eedbbb530c7cd11bd13ac07397d69c Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Fri, 3 Jul 2026 13:34:19 +0100 Subject: [PATCH 40/60] build: update min versions --- Gemfile | 4 ++-- jsonapi-resources.gemspec | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Gemfile b/Gemfile index 805949eb6..2dc5e6be9 100644 --- a/Gemfile +++ b/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec platforms :ruby do - gem 'sqlite3', '>= 1.4' + gem 'sqlite3', '>= 2.1' end platforms :jruby do @@ -17,7 +17,7 @@ when 'master' gem 'railties', { git: 'https://github.com/rails/rails.git' } gem 'arel', { git: 'https://github.com/rails/arel.git' } when 'default' - gem 'railties', '~> 7.1.0' + gem 'railties', '~> 8.0.0' else gem 'railties', "~> #{version}" end diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 9942ddf9e..9df9d299c 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -17,7 +17,7 @@ Gem::Specification.new do |spec| spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] - spec.required_ruby_version = '>= 2.1' + spec.required_ruby_version = '>= 3.2' spec.add_development_dependency 'bundler', '>= 1.5', '< 3.0' spec.add_development_dependency 'rake' From 4644f642503066cef8c9ee88b2a5003b8af9cf18 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:35:55 +0100 Subject: [PATCH 41/60] build: add rack 3 as a dependency --- jsonapi-resources.gemspec | 1 + 1 file changed, 1 insertion(+) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 9df9d299c..1f2e37b4f 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -28,6 +28,7 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'concurrent-ruby-ext' spec.add_dependency 'activerecord', '>= 4.1' spec.add_dependency 'railties', '>= 4.1' + spec.add_dependency 'rack', '~> 3.0' spec.add_dependency 'concurrent-ruby' spec.add_runtime_dependency 'csv' end From 91db2a05afc20acb777f94936cd0b6c44861ae07 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Fri, 3 Jul 2026 13:58:51 +0100 Subject: [PATCH 42/60] build: add minitest-mock as a development dependency cannot load such file -- minitest/mock (LoadError) --- jsonapi-resources.gemspec | 1 + 1 file changed, 1 insertion(+) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 1f2e37b4f..c860df509 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -22,6 +22,7 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'bundler', '>= 1.5', '< 3.0' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest' + spec.add_development_dependency 'minitest-mock' spec.add_development_dependency 'minitest-spec-rails' spec.add_development_dependency 'simplecov' spec.add_development_dependency 'pry' From e09c2be2ab5dc5912ce9e6c25e46de643ac22929 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:38:18 +0100 Subject: [PATCH 43/60] fix: unprocessable_entity -> unprocessable_content --- lib/jsonapi/exceptions.rb | 4 ++-- test/controllers/controller_test.rb | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/jsonapi/exceptions.rb b/lib/jsonapi/exceptions.rb index cf77dfd12..feabb58ce 100644 --- a/lib/jsonapi/exceptions.rb +++ b/lib/jsonapi/exceptions.rb @@ -475,7 +475,7 @@ def errors def json_api_error(attr_key, message) create_error_object(code: JSONAPI::VALIDATION_ERROR, - status: :unprocessable_entity, + status: :unprocessable_content, title: message, detail: "#{format_key(attr_key)} - #{message}", source: { pointer: pointer(attr_key) }, @@ -500,7 +500,7 @@ def pointer(attr_or_relationship_name) class SaveFailed < Error def errors [create_error_object(code: JSONAPI::SAVE_FAILED, - status: :unprocessable_entity, + status: :unprocessable_content, title: I18n.translate('jsonapi-resources.exceptions.save_failed.title', default: 'Save failed or was cancelled'), detail: I18n.translate('jsonapi-resources.exceptions.save_failed.detail', diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index 7bdf19c2d..fb4de6472 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -615,7 +615,7 @@ def test_create_link_to_missing_object } } - assert_response :unprocessable_entity + assert_response :unprocessable_content # TODO: check if this validation is working assert_match /author - can't be blank/, response.body assert_equal nil, response.location @@ -698,7 +698,7 @@ def test_create_with_invalid_data } } - assert_response :unprocessable_entity + assert_response :unprocessable_content assert_equal "/data/relationships/author", json_response['errors'][0]['source']['pointer'] assert_equal "can't be blank", json_response['errors'][0]['title'] @@ -1832,7 +1832,7 @@ def test_delete_with_validation_error delete :destroy, params: { id: post.id } assert_equal "can't destroy me", json_response['errors'][0]['title'] - assert_response :unprocessable_entity + assert_response :unprocessable_content end def test_delete_single @@ -2380,7 +2380,7 @@ def test_create_validations_missing_attribute } } - assert_response :unprocessable_entity + assert_response :unprocessable_content assert_equal 2, json_response['errors'].size assert_equal JSONAPI::VALIDATION_ERROR, json_response['errors'][0]['code'] assert_equal JSONAPI::VALIDATION_ERROR, json_response['errors'][1]['code'] @@ -2402,7 +2402,7 @@ def test_update_validations_missing_attribute } } - assert_response :unprocessable_entity + assert_response :unprocessable_content assert_equal 1, json_response['errors'].size assert_equal JSONAPI::VALIDATION_ERROR, json_response['errors'][0]['code'] assert_match /name - can't be blank/, response.body @@ -2854,7 +2854,7 @@ def test_create_with_invalid_data } } - assert_response :unprocessable_entity + assert_response :unprocessable_content assert_equal "/data/attributes/spouse-name", json_response['errors'][0]['source']['pointer'] assert_equal "can't be blank", json_response['errors'][0]['title'] @@ -3402,7 +3402,7 @@ def test_save_model_callbacks_fail } } - assert_response :unprocessable_entity + assert_response :unprocessable_content assert_match /Save failed or was cancelled/, json_response['errors'][0]['detail'] end end From a1a647752eb0998b1d7430b892c6257aaf97b2e8 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:47:22 +0100 Subject: [PATCH 44/60] build: limit rails versions to 8.0.x --- jsonapi-resources.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index c860df509..b238f8547 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -27,8 +27,8 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'simplecov' spec.add_development_dependency 'pry' spec.add_development_dependency 'concurrent-ruby-ext' - spec.add_dependency 'activerecord', '>= 4.1' - spec.add_dependency 'railties', '>= 4.1' + spec.add_dependency 'activerecord', '~> 8.0.0' + spec.add_dependency 'railties', '~> 8.0.0' spec.add_dependency 'rack', '~> 3.0' spec.add_dependency 'concurrent-ruby' spec.add_runtime_dependency 'csv' From f611b05df4c1f8a46a63ddb370a80e65c06ffc4c Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:54:32 +0100 Subject: [PATCH 45/60] build: relax rails versions to include 7.1 and 7.2 --- jsonapi-resources.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index b238f8547..148f54f12 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -27,8 +27,8 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'simplecov' spec.add_development_dependency 'pry' spec.add_development_dependency 'concurrent-ruby-ext' - spec.add_dependency 'activerecord', '~> 8.0.0' - spec.add_dependency 'railties', '~> 8.0.0' + spec.add_dependency 'activerecord', '>= 7.1', '<= 8.1' # versions 7.1, 7.2, 8.0 + spec.add_dependency 'railties', '>= 7.1', '<= 8.1' # versions 7.1, 7.2, 8.0 spec.add_dependency 'rack', '~> 3.0' spec.add_dependency 'concurrent-ruby' spec.add_runtime_dependency 'csv' From 6e06185aad06820b6aa0c4e3aefc1d2399a23243 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:56:55 +0100 Subject: [PATCH 46/60] build: fix version restiction typo --- jsonapi-resources.gemspec | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index 148f54f12..ef0cb2d48 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -27,8 +27,8 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'simplecov' spec.add_development_dependency 'pry' spec.add_development_dependency 'concurrent-ruby-ext' - spec.add_dependency 'activerecord', '>= 7.1', '<= 8.1' # versions 7.1, 7.2, 8.0 - spec.add_dependency 'railties', '>= 7.1', '<= 8.1' # versions 7.1, 7.2, 8.0 + spec.add_dependency 'activerecord', '>= 7.1', '< 8.1' # versions 7.1, 7.2, 8.0 + spec.add_dependency 'railties', '>= 7.1', '< 8.1' # versions 7.1, 7.2, 8.0 spec.add_dependency 'rack', '~> 3.0' spec.add_dependency 'concurrent-ruby' spec.add_runtime_dependency 'csv' From f043d674d1a813ef60b5c494c51427251cda156e Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 11:57:26 +0100 Subject: [PATCH 47/60] release: bump version --- lib/jsonapi/resources/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resources/version.rb b/lib/jsonapi/resources/version.rb index 07ba6bd5f..d9a2c2bad 100644 --- a/lib/jsonapi/resources/version.rb +++ b/lib/jsonapi/resources/version.rb @@ -1,5 +1,5 @@ module JSONAPI module Resources - VERSION = '0.1.2' + VERSION = '0.1.3' end end From 564c9d80a2bf14c7cbe85d7263466e1a27b4c704 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 12:48:17 +0100 Subject: [PATCH 48/60] fix: replace updated Rack status_code function with legacy version --- lib/jsonapi/error.rb | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/error.rb b/lib/jsonapi/error.rb index fc39d93aa..00bee7a20 100644 --- a/lib/jsonapi/error.rb +++ b/lib/jsonapi/error.rb @@ -15,7 +15,7 @@ def initialize(options = {}) @source = options[:source] @links = options[:links] - @status = Rack::Utils.status_code(options[:status]).to_s + @status = status_code(options[:status]).to_s @meta = options[:meta] end @@ -24,6 +24,17 @@ def to_hash instance_variables.each {|var| hash[var.to_s.delete('@')] = instance_variable_get(var) unless instance_variable_get(var).nil? } hash end + + private + + # Extracted from Rack 2 + def status_code(status) + if status.is_a?(Symbol) + Rack::Utils.SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" } + else + status.to_i + end + end end class Warning From 1ad672697ecb48b3c8d7a1b4b182b9ebb8d37a2d Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:02:43 +0100 Subject: [PATCH 49/60] test: repair test runner not being invoked --- test/test_helper.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_helper.rb b/test/test_helper.rb index dd956e077..f0a968e8f 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -20,6 +20,7 @@ require 'active_record/railtie' require 'minitest/mock' +require 'minitest/autorun' require 'jsonapi-resources' require 'pry' From 1f08ebd27e3963ca5d0a24a3b922970f0b2a7dd9 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:06:27 +0100 Subject: [PATCH 50/60] fix: remove use of deprecated URI::Escape --- lib/jsonapi/request_parser.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/jsonapi/request_parser.rb b/lib/jsonapi/request_parser.rb index c7e0d6efa..aa34e4f31 100644 --- a/lib/jsonapi/request_parser.rb +++ b/lib/jsonapi/request_parser.rb @@ -1,5 +1,6 @@ require 'jsonapi/operation' require 'jsonapi/paginator' +require 'cgi' module JSONAPI class RequestParser @@ -272,7 +273,7 @@ def parse_sort_criteria(sort_criteria) sorts = [] begin - raw = URI.unescape(sort_criteria) + raw = CGI.unescape(sort_criteria) sorts += CSV.parse_line(raw) rescue CSV::MalformedCSVError fail JSONAPI::Exceptions::InvalidSortCriteria.new(format_key(@resource_klass._type), raw) From d1da2261258e26562d616a036557eb9962e1508e Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:09:43 +0100 Subject: [PATCH 51/60] test: repair old ruby 2 -> 3 errors --- test/fixtures/active_record.rb | 2 +- test/test_helper.rb | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/fixtures/active_record.rb b/test/fixtures/active_record.rb index 9a958fa2e..d595785ea 100644 --- a/test/fixtures/active_record.rb +++ b/test/fixtures/active_record.rb @@ -350,7 +350,7 @@ class Post < ActiveRecord::Base has_many :comments has_and_belongs_to_many :tags, join_table: :posts_tags has_many :special_post_tags - has_many :special_tags, through: :special_post_tags + has_many :special_tags, through: :special_post_tags, source: :tag belongs_to :section has_one :parent_post, class_name: 'Post', foreign_key: 'parent_post_id' diff --git a/test/test_helper.rb b/test/test_helper.rb index f0a968e8f..3003ad027 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -79,9 +79,9 @@ class Engine < ::Rails::Engine # Monkeypatch ActionController::TestCase to delete the RAW_POST_DATA on subsequent calls in the same test. if Rails::VERSION::MAJOR >= 5 module ClearRawPostHeader - def process(action, *args) + def process(action, *args, **kwargs) @request.delete_header 'RAW_POST_DATA' - super + super(action, *args, **kwargs) end end @@ -490,13 +490,13 @@ def assert_cacheable_jsonapi_get(url, cached_classes = :all) end class ActionController::TestCase - def assert_cacheable_get(action, *args) + def assert_cacheable_get(action, **request_options) assert_nil JSONAPI.configuration.resource_cache normal_queries = [] normal_query_callback = lambda {|_, _, _, _, payload| normal_queries.push payload[:sql] } ActiveSupport::Notifications.subscribed(normal_query_callback, 'sql.active_record') do - get action, *args + get action, **request_options end non_caching_response = json_response_sans_backtraces non_caching_status = response.status @@ -530,7 +530,7 @@ def assert_cacheable_get(action, *args) @controller = nil setup_controller_request_and_response @request.headers.merge!(orig_request_headers.dup) - get action, *args + get action, **request_options end end rescue Exception From f93435f087a59550b4af25f6857b840654a16bc9 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:12:20 +0100 Subject: [PATCH 52/60] test: add errors using modern rails idiom --- test/unit/resource/resource_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit/resource/resource_test.rb b/test/unit/resource/resource_test.rb index 83c417c61..46c19b80b 100644 --- a/test/unit/resource/resource_test.rb +++ b/test/unit/resource/resource_test.rb @@ -13,7 +13,7 @@ class PostWithBadAfterSave < ActiveRecord::Base after_save :do_some_after_save_stuff def do_some_after_save_stuff - errors[:base] << 'Boom! Error added in after_save callback.' + errors.add(:base, 'Boom! Error added in after_save callback.') raise ActiveRecord::RecordInvalid.new(self) end end @@ -23,7 +23,7 @@ class PostWithCustomValidationContext < ActiveRecord::Base validate :api_specific_check, on: :json_api_create def api_specific_check - errors[:base] << 'Record is invalid' + errors.add(:base, 'Record is invalid') end end From 0f4f8c295750119694a778d5c2895edee7abf043 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:13:48 +0100 Subject: [PATCH 53/60] test: fix nil assertion warnings --- test/controllers/controller_test.rb | 34 +++++++++---------- .../operation/operation_dispatcher_test.rb | 2 +- test/unit/serializer/link_builder_test.rb | 3 +- 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/test/controllers/controller_test.rb b/test/controllers/controller_test.rb index fb4de6472..48cde639a 100644 --- a/test/controllers/controller_test.rb +++ b/test/controllers/controller_test.rb @@ -483,7 +483,7 @@ def test_show_does_not_include_records_count_in_meta JSONAPI.configuration.top_level_meta_include_record_count = true assert_cacheable_get :show, params: { id: Post.first.id } assert_response :success - assert_equal json_response['meta'], nil + assert_nil json_response['meta'] ensure JSONAPI.configuration.top_level_meta_include_record_count = false end @@ -492,7 +492,7 @@ def test_show_does_not_include_pages_count_in_meta JSONAPI.configuration.top_level_meta_include_page_count = true assert_cacheable_get :show, params: { id: Post.first.id } assert_response :success - assert_equal json_response['meta'], nil + assert_nil json_response['meta'] ensure JSONAPI.configuration.top_level_meta_include_page_count = false end @@ -596,7 +596,7 @@ def test_create_simple_id_not_allowed assert_response :bad_request assert_match /id is not allowed/, response.body - assert_equal nil,response.location + assert_nil response.location end def test_create_link_to_missing_object @@ -618,7 +618,7 @@ def test_create_link_to_missing_object assert_response :unprocessable_content # TODO: check if this validation is working assert_match /author - can't be blank/, response.body - assert_equal nil, response.location + assert_nil response.location end def test_create_extra_param @@ -640,7 +640,7 @@ def test_create_extra_param assert_response :bad_request assert_match /asdfg is not allowed/, response.body - assert_equal nil,response.location + assert_nil response.location end def test_create_extra_param_allow_extra_params @@ -707,7 +707,7 @@ def test_create_with_invalid_data assert_equal "/data/attributes/title", json_response['errors'][1]['source']['pointer'] assert_equal "is too long (maximum is 35 characters)", json_response['errors'][1]['title'] assert_equal "title - is too long (maximum is 35 characters)", json_response['errors'][1]['detail'] - assert_equal nil, response.location + assert_nil response.location end def test_create_multiple @@ -760,7 +760,7 @@ def test_create_simple_missing_posts assert_response :bad_request assert_match /The required parameter, data, is missing./, json_response['errors'][0]['detail'] - assert_equal nil, response.location + assert_nil response.location end def test_create_simple_wrong_type @@ -781,7 +781,7 @@ def test_create_simple_wrong_type assert_response :bad_request assert_match /posts_spelled_wrong is not a valid resource./, json_response['errors'][0]['detail'] - assert_equal nil, response.location + assert_nil response.location end def test_create_simple_missing_type @@ -801,7 +801,7 @@ def test_create_simple_missing_type assert_response :bad_request assert_match /The required parameter, type, is missing./, json_response['errors'][0]['detail'] - assert_equal nil, response.location + assert_nil response.location end def test_create_simple_unpermitted_attributes @@ -822,7 +822,7 @@ def test_create_simple_unpermitted_attributes assert_response :bad_request assert_match /subject/, json_response['errors'][0]['detail'] - assert_equal nil, response.location + assert_nil response.location end def test_create_simple_unpermitted_attributes_allow_extra_params @@ -1086,7 +1086,7 @@ def test_update_remove_links assert_response :success assert json_response['data'].is_a?(Hash) assert_equal '3', json_response['data']['relationships']['author']['data']['id'] - assert_equal nil, json_response['data']['relationships']['section']['data'] + assert_nil json_response['data']['relationships']['section']['data'] assert_equal 'A great new Post', json_response['data']['attributes']['title'] assert_equal 'AAAA', json_response['data']['attributes']['body'] assert matches_array?([], @@ -1116,7 +1116,7 @@ def test_update_relationship_to_one_nil assert_response :no_content post_object = Post.find(4) - assert_equal nil, post_object.section_id + assert_nil post_object.section_id end def test_update_relationship_to_one_invalid_links_hash_keys_ids @@ -1233,7 +1233,7 @@ def test_update_relationship_to_one_singular_param_id_nil put :update_relationship, params: {post_id: 3, relationship: 'section', data: {type: 'sections', id: nil}} assert_response :no_content - assert_equal nil, post_object.reload.section_id + assert_nil post_object.reload.section_id end def test_update_relationship_to_one_data_nil @@ -1246,7 +1246,7 @@ def test_update_relationship_to_one_data_nil put :update_relationship, params: {post_id: 3, relationship: 'section', data: nil} assert_response :no_content - assert_equal nil, post_object.reload.section_id + assert_nil post_object.reload.section_id end def test_remove_relationship_to_one @@ -1260,7 +1260,7 @@ def test_remove_relationship_to_one assert_response :no_content post_object = Post.find(3) - assert_equal nil, post_object.section_id + assert_nil post_object.section_id end def test_update_relationship_to_one_singular_param @@ -2546,7 +2546,7 @@ def test_get_person_as_author assert_equal '1', json_response['data'][0]['id'] assert_equal 'authors', json_response['data'][0]['type'] assert_equal 'Joe Author', json_response['data'][0]['attributes']['name'] - assert_equal nil, json_response['data'][0]['attributes']['email'] + assert_nil json_response['data'][0]['attributes']['email'] end def test_show_person_as_author @@ -2555,7 +2555,7 @@ def test_show_person_as_author assert_equal '1', json_response['data']['id'] assert_equal 'authors', json_response['data']['type'] assert_equal 'Joe Author', json_response['data']['attributes']['name'] - assert_equal nil, json_response['data']['attributes']['email'] + assert_nil json_response['data']['attributes']['email'] end def test_get_person_as_author_by_name_filter diff --git a/test/unit/operation/operation_dispatcher_test.rb b/test/unit/operation/operation_dispatcher_test.rb index 278ebd6dd..f7816e583 100644 --- a/test/unit/operation/operation_dispatcher_test.rb +++ b/test/unit/operation/operation_dispatcher_test.rb @@ -85,7 +85,7 @@ def test_replace_to_one_relationship op.process(operations) saturn.reload - assert_equal(saturn.planet_type_id, nil) + assert_nil(saturn.planet_type_id) # Reset operations = [ diff --git a/test/unit/serializer/link_builder_test.rb b/test/unit/serializer/link_builder_test.rb index e1062280b..0935474ae 100644 --- a/test/unit/serializer/link_builder_test.rb +++ b/test/unit/serializer/link_builder_test.rb @@ -39,8 +39,7 @@ def test_engine_name primary_resource_klass: ApiV2Engine::PersonResource ).engine_name - assert_equal nil, - JSONAPI::LinkBuilder.new( + assert_nil JSONAPI::LinkBuilder.new( primary_resource_klass: Api::V1::PersonResource ).engine_name end From 4ae344d42ca635fc40874b7e03d6487da035cb7b Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:19:15 +0100 Subject: [PATCH 54/60] build: add minitest reporters for better test feedback --- jsonapi-resources.gemspec | 1 + test/test_helper.rb | 3 +++ 2 files changed, 4 insertions(+) diff --git a/jsonapi-resources.gemspec b/jsonapi-resources.gemspec index ef0cb2d48..7b5e13975 100644 --- a/jsonapi-resources.gemspec +++ b/jsonapi-resources.gemspec @@ -24,6 +24,7 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'minitest' spec.add_development_dependency 'minitest-mock' spec.add_development_dependency 'minitest-spec-rails' + spec.add_development_dependency 'minitest-reporters' spec.add_development_dependency 'simplecov' spec.add_development_dependency 'pry' spec.add_development_dependency 'concurrent-ruby-ext' diff --git a/test/test_helper.rb b/test/test_helper.rb index 3003ad027..a74f4a18e 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -21,6 +21,7 @@ require 'active_record/railtie' require 'minitest/mock' require 'minitest/autorun' +require 'minitest/reporters' require 'jsonapi-resources' require 'pry' @@ -29,6 +30,8 @@ require File.expand_path('../helpers/functional_helpers', __FILE__) require File.expand_path('../helpers/configuration_helpers', __FILE__) +Minitest::Reporters.use! + Rails.env = 'test' I18n.load_path += Dir[File.expand_path("../../locales/*.yml", __FILE__)] From c823ea9f125b9e059490fd493685bdfc3e4087c6 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:23:30 +0100 Subject: [PATCH 55/60] fix: repair method typo --- lib/jsonapi/error.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/error.rb b/lib/jsonapi/error.rb index 00bee7a20..89ff65902 100644 --- a/lib/jsonapi/error.rb +++ b/lib/jsonapi/error.rb @@ -30,7 +30,7 @@ def to_hash # Extracted from Rack 2 def status_code(status) if status.is_a?(Symbol) - Rack::Utils.SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" } + Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" } else status.to_i end From 609d51b977e882dab4661c84b413eea4d7f81535 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:34:28 +0100 Subject: [PATCH 56/60] fix: use Rails 7 deprecation warnings --- lib/jsonapi/resource.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/jsonapi/resource.rb b/lib/jsonapi/resource.rb index efaae4635..05eff7925 100644 --- a/lib/jsonapi/resource.rb +++ b/lib/jsonapi/resource.rb @@ -511,7 +511,7 @@ def attribute(attr, options = {}) check_reserved_attribute_name(attr) if (attr.to_sym == :id) && (options[:format].nil?) - ActiveSupport::Deprecation.warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.') + ActiveSupport::Deprecation.new(nil, 'JSONAPI').warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.') end check_duplicate_attribute_name(attr) if options[:format].nil? From 2255afb7d416fe83cf175d66d3c33d694e5765d1 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Tue, 11 Aug 2026 14:42:57 +0100 Subject: [PATCH 57/60] test: add additional unprocessable content tests --- test/integration/requests/request_test.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/integration/requests/request_test.rb b/test/integration/requests/request_test.rb index 31821f8fd..f6ff20e7c 100644 --- a/test/integration/requests/request_test.rb +++ b/test/integration/requests/request_test.rb @@ -256,6 +256,9 @@ def test_post_single_minimal_invalid } assert_jsonapi_response 422 + assert_equal JSONAPI::VALIDATION_ERROR, json_response['errors'][0]['code'] + assert_equal '422', json_response['errors'][0]['status'] + assert_match "can't be blank", json_response['errors'][0]['title'] end def test_update_relationship_without_content_type From ef3aa762dfa87a15e3011aa8d7fc97702cf6acbf Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Wed, 12 Aug 2026 14:30:10 +0100 Subject: [PATCH 58/60] test: add json-api error tests --- .../jsonapi_request/jsonapi_error_test.rb | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 test/unit/jsonapi_request/jsonapi_error_test.rb diff --git a/test/unit/jsonapi_request/jsonapi_error_test.rb b/test/unit/jsonapi_request/jsonapi_error_test.rb new file mode 100644 index 000000000..078971d8c --- /dev/null +++ b/test/unit/jsonapi_request/jsonapi_error_test.rb @@ -0,0 +1,41 @@ +require File.expand_path('../../../test_helper', __FILE__) + +class JSONAPIErrorTest < Minitest::Test + def test_status_code_no_status + error = JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST) + + assert_equal('0', error.status) + end + + def test_status_code_accepts_symbol + error = JSONAPI::Error.new(code: JSONAPI::VALIDATION_ERROR, status: :unprocessable_content) + + assert_equal('422', error.status) + end + + def test_status_code_accepts_integer + error = JSONAPI::Error.new(code: JSONAPI::VALIDATION_ERROR, status: 422) + + assert_equal('422', error.status) + end + + def test_status_code_accepts_string + error = JSONAPI::Error.new(code: JSONAPI::VALIDATION_ERROR, status: '422') + + assert_equal('422', error.status) + end + + def test_status_code_rejects_unknown_symbol + error = assert_raises(ArgumentError) do + JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, status: :not_a_real_status) + end + + assert_equal('Unrecognized status code :not_a_real_status', error.message) + end + + def test_status_code_handles_nil + error = JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, status: nil) + + assert_equal('0', error.status) + end +end From f068db948684511f5b58394e01c2ccc52afff572 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Wed, 12 Aug 2026 14:33:44 +0100 Subject: [PATCH 59/60] test: ignore temporary test files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 6cc125d63..ec4e88afd 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ coverage test/log test_db test_db-journal +test/test_db-* From 73b5ed1213013b721fba787eab6d2fd34e44bb79 Mon Sep 17 00:00:00 2001 From: Stephen Hulme Date: Wed, 12 Aug 2026 14:35:03 +0100 Subject: [PATCH 60/60] fix: raise ArgumentError for nil status --- lib/jsonapi/error.rb | 4 ++++ test/unit/jsonapi_request/jsonapi_error_test.rb | 16 ++++++++++------ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/jsonapi/error.rb b/lib/jsonapi/error.rb index 89ff65902..3fafdd2a1 100644 --- a/lib/jsonapi/error.rb +++ b/lib/jsonapi/error.rb @@ -29,6 +29,10 @@ def to_hash # Extracted from Rack 2 def status_code(status) + if status.nil? + raise ArgumentError, "Status code is required" + end + if status.is_a?(Symbol) Rack::Utils::SYMBOL_TO_STATUS_CODE.fetch(status) { raise ArgumentError, "Unrecognized status code #{status.inspect}" } else diff --git a/test/unit/jsonapi_request/jsonapi_error_test.rb b/test/unit/jsonapi_request/jsonapi_error_test.rb index 078971d8c..801b8204d 100644 --- a/test/unit/jsonapi_request/jsonapi_error_test.rb +++ b/test/unit/jsonapi_request/jsonapi_error_test.rb @@ -1,10 +1,12 @@ require File.expand_path('../../../test_helper', __FILE__) class JSONAPIErrorTest < Minitest::Test - def test_status_code_no_status - error = JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST) + def test_status_code_requires_status + error = assert_raises(ArgumentError) do + JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST) + end - assert_equal('0', error.status) + assert_equal('Status code is required', error.message) end def test_status_code_accepts_symbol @@ -33,9 +35,11 @@ def test_status_code_rejects_unknown_symbol assert_equal('Unrecognized status code :not_a_real_status', error.message) end - def test_status_code_handles_nil - error = JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, status: nil) + def test_status_code_rejects_nil + error = assert_raises(ArgumentError) do + JSONAPI::Error.new(code: JSONAPI::BAD_REQUEST, status: nil) + end - assert_equal('0', error.status) + assert_equal('Status code is required', error.message) end end