Skip to content

Using Operation Processes to add to returned payload meta

Sean Moe edited this page Dec 15, 2017 · 2 revisions

There may come a time when you want to affect the meta of the returned payload and not just the individual resources that are returned. To do this, Operation Processors come in very handy.

Problem: We want to create a resource that allows a client to play with a set of books. At the same time, we want to return a list of all available authors and genres so the client can create a menu of available search options. If the client simply loops through the list of returned books, it will only know about the authors and genres located within the returned results which will most likely be limited by pagination.

Solution: Use an Operation Processor to add the authors and genres in the meta of the returned payload.

Note: This author, book, genre example is just that, an example. It is your responsibility to understand the potential side affects of potentially returning very large lists in meta.

module API
  module V3
    class BookController < API::V3::BaseController
    end

    class BookProcessor < JSONAPI::Processor
      after_find do
        unless @result.is_a?(JSONAPI::ErrorsOperationResult)
          author = @result.resources.map(&:author).uniq.compact
          genres = @result.resources.map(&:genre).uniq.compact
          @result.meta[:authors] = authors
          @result.meta[:genres] = genres
        end
      end
    end
  end
end