1

I've been struggling to apply JSON-API resources with service object. Here is my rough draft,

class V1::AccountCreateController < JSONAPI::ResourceController
  def create
    # Form object for the parameter validation
    form = AccountCreateCustomerForm.new customer_params
    form.validate!

    # Use my service object instead of JR's 1:1 mapping to the ActiveRecord model to create it.
    account = AccountCreateService.call(form.attributes)
    if account.errors.blank?
        # selialize the result and rednder
        serializer = JSONAPI::ResourceSerializer.new(resource_klass, ...)
       render json: serializer.serialize_to_hash(resource_klass.new(account)), status: 201
    else
       render render json: 'error message', status: 422
    end
  end
end

This actually works. However I don't think it's clean.

I think JSON-API resource is not supposed to use with service object.

I need to post third party API (Stripe) for data processing not only local db, which made my life easier to develop robust & testable payment system. (No callbacks.)

However with JSON-API it's pretty hard to deal with service object. (For Create/Update/Destroy action.)

Any ideas to work around this?

It would be really helpful if you could post some examples too.

P.S I use dry-validation for form object.

Toshi
  • 6,012
  • 8
  • 35
  • 58
  • Did you try looking on the demo app (https://github.com/cerebris/peeps)? You need to keep your controller empty and deal with your logic in resource callbacks (http://jsonapi-resources.com/v0.8/guide/resources.html#Callbacks). As for validations, they need to be part of the model. You can also use Pundit gem as described in http://jsonapi-resources.com/v0.8/guide/authorization.html – Guy Segev Feb 05 '17 at 14:50
  • I would recommend AMS for JSON API https://github.com/rails-api/active_model_serializers/blob/master/docs/general/getting_started.md – XY L Feb 21 '17 at 09:26

0 Answers0