Giter Site home page Giter Site logo

infinum / json_api_responders Goto Github PK

View Code? Open in Web Editor NEW

This project forked from monorkin/json_api_responders

26.0 10.0 3.0 78 KB

Responders for your Rails JSON API apps.

License: MIT License

Ruby 99.37% Shell 0.63%
json-api rails responder ruby

json_api_responders's Introduction

JsonApiResponders

Gem Version Build Status Maintainability Test Coverage

This gem gives a few convenient methods for working with JSONAPI. It is inspired by the responders gem.

Installation

Add this line to your application's Gemfile:

gem 'json_api_responders'

And then execute:

$ bundle

Inside your base controller, include the module:

module Api
  module V1
    class BaseController < ApplicationController
      include JsonApiResponders
    end
  end
end

Usage

This gem comes with the two following methods respond_with and respond_with_error.

respond_with(resource, options = {})

This method requires a resource as a parameter, and you can pass some options if you wish. Any options you do choose to pass into respond_with will be passed on to the controller.render method. In the Configuration section you can learn how to set mandatory options. Bellow you will find a few examples on how to use this method:

user = User.first
respond_with user

The above example will render the User object.

user = User.first
respond_with user, on_error: { 
: :unauthorized, detail: 'Invalid user or password' }

The above example will render an Error response if an error would occur.

respond_with_error(status, detail = nil)

This method requires HTTP status code and an optional parameter explaining the error. This method will render an error message as described in the JSON API specification. Below you can see an example of how it should be used:

respond_with_error(401, 'Bad credentials')
respond_with_error(404, 'Not found')
respond_with_error(400, 'Bad request')

Configuration

Currently you can only configure which options are required to be passed through the respond_with method. These required options are categorized by the controller's actions. Bellow you can find an example:

# config/initializers/json_api_responders.rb
JsonApiResponders.configure do |config|
    config.required_options = {
      index: [:each_serializer],
      create: [:serializer]
    }
end

# app/controllers/v1/users_controller.rb
def create
  user = User.create(...)
  respond_with user, serializer: UserSerializer
end

If :serializer was left out of the above respond_with method you would see the JsonApiResponders::Errors::RequiredOptionMissingError be raised.

Responses

index

render json: resource, status: 200

show

render json: resource, status: 200

create

if resource.valid?
  render json: resource, status: 201
else
  render error: errors, status: 409
end

update

if resource.valid?
  render json: resource, status: 200
else
  render error: errors, status: 409
end

destroy

head status: 204

Error translations

json_api_responders has translation support for error title and details. Copy & paste this file to your config/locales folder:

en:
  json_api:
    errors:
      not_found:
        title: Not found
        detail: Resource not found
      forbidden:
        title: Unauthorized
        detail: User is not authorized to use this resource
      unprocessable_entity:
        title: Unprocessable Entity
        details: Cannot process request
      conflict:
        title: Invalid Attribute
        details: Something is missing

It translates using the format I18n.t("json_api.errors.#{human_readable_status_code}.title")

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/infinum/json_api_responders.

json_api_responders's People

Contributors

anamarijabalaban avatar d4be4st avatar damirsvrtan avatar fsuste avatar lovro-bikic avatar maksar avatar monorkin avatar nikone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json_api_responders's Issues

Don't return full error messages in error response

We had a case where we needed to add some custom error messages on some attributes.

Since this gem used resource.errors.full_messages, error messages would be weird, e.g. "Shipping address some of the line items can't be delivered to this shipping address" instead of just "Some of the line items can't be delivered to this shipping address".

We monkey patched a solution for this:

def error_render_options
    errors = { errors: [] }

    errors[:errors] << { detail: on_error(:detail) } if on_error(:detail)

    resource.errors.messages.each do |attribute, messages|
      messages.each do |message|
        errors[:errors] << error_response(attribute, message)
      end
    end if resource.respond_to?(:errors)

    errors
  end

  def error_response(attribute, message)
    {
      title: I18n.t("json_api.errors.#{status}.title"),
      detail: message.capitalize,
      source: { parameter: attribute, pointer: "data/attributes/#{attribute}" }
    }
  end

Error required when serializer is not specified

With the new update we are required to specify the exact serializer, and when working with old code, this can be a pain to debug. When the serializer is not specified, the issue shows up later in the code, and there is no indication that the issue arises from the #respond_with method.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.