2

I'm building a JSON API for clients that need meaningful, specific errors. Everything has been going swimmingly for endpoints involving a single resource type, but we're facing challenges for requests involving multiple resource types (all operations should fail if one does).

One idea we're considering is having clients submit an array of operations that resemble single-resource requests and returning an array containing a response to each. Then we could wrap all calls in a transaction and roll it back if a resource fails to save.

A request might look like this:

{
  "operations": [
     {
       "path": "/orders",
       "action": "POST",
       "data": {
         "client_id": 1
       }
     },
     {
       "path": "/charges",
       "action": "POST",
       "data": {
         "amount": 300,
       },
       "relationships": {
         "order": {
           "id": {
             "pointer": { "/operations/0/data" }
           }
         }
       }
     }
  ]
}

And a response might look like:

{
  "operations": [
    {
      "status": "201",
      "data": {}
    },
    {
      "status": "400",
      "errors": [...]
    }
  ]
}

So I'm wondering if it would be possible for an endpoint to programmatically call the existing, associated actions (e.g., OrdersController#create and ChargesController#create) within a transaction, collect their rendered responses, and render those responses as an array back to the client.

In my mind, the challenges seem to be:

  • Resolving paths to controller actions
  • Including correct params in each action

Any help is much appreciated--even if that help is "why would you ever want to do that?!? Do this instead!" Thanks!

1 Answer 1

1

This sounds like a really bad idea as it's going against the way Rails (and also HTTP) is designed to be used. Try moving logic out of controllers into reusable services which can be called from any Controller action, wrapped in transactions and handle errors any way you want..

Sign up to request clarification or add additional context in comments.

1 Comment

I figured this might be the case. I've been using PORO "services" from controllers, but I was hoping there might be some relatively easy way to create a relatively abstract one to re-use the existing single-resource endpoints. Thanks for the response!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.