0
\$\begingroup\$

I'm creating an API endpoint to create and delete associations, essential creating and deleting records of a join model.

The code below doesn't seem idiomatic or pragmatic at all. What's the best way to create 2 endpoints, POST and DELETE for the same route?

module API
  module V1
    class UserActivities < Grape::API
      include API::V1::Defaults

      format :json

      namespace :users do

        route_param :user_id do
          resource :activities do
            desc 'Create User + Activity associations'
            route_param :activity_id do
              post do
                #pyramid of doom
              end
            end
          end

          resource :activities do
            desc 'Delete User + Activity associations'
            route_param :activity_id do
              delete do
                #pyramid of doom
              end
            end
          end
        end
      end
    end
  end
end

This generates the following routes:

   POST  |  /api/:version/users/:user_id/activities/:activity_id(.:format)  |  v1  |  Create User + Activity associations
 DELETE  |  /api/:version/users/:user_id/activities/:activity_id(.:format)  |  v1  |  Delete User + Activity associations

But is there a better way to do this using Grape?

\$\endgroup\$
2
\$\begingroup\$

You don't have to define the whole flow per route, this still leads you to the pyramid of hell.

  namespace :users do
    route_param :user_id do
      resource :activities do
        desc 'Create User + Activity associations'
        route_param :activity_id do
          post do
            #pyramid of doom
          end

          delete do
            #pyramid of doom
          end
        end
      end
    end
  end

However, you can register parts of the route in different files

namespace :users do
  register UserActivities
end

Then, within user_activities.rb you can add the rest of the code

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.