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.