grape-throttle icon indicating copy to clipboard operation
grape-throttle copied to clipboard

Different limit based on user group

Open confact opened this issue 10 years ago • 2 comments

I have different user levels (normal users and VIP users) which i want to give different limits too. How do i do that in a good way here? Is it even possible?

confact avatar Nov 24 '15 20:11 confact

Not at the moment, but that sounds like a great idea. At a quick thought, here's an idea for how the end-user code might look.

desc "Start competition"
throttle vip: { period: 10.minutes, limit: 1 }, normal: { period: 12.minutes, limit: 3 }
params do
  requires :id, type: Integer, desc: "id"
end
post "/:id/competition" do
  User.find(params[:id]).start_competition
end

Middleware

use Grape::Middleware::ThrottleMiddleware, cache: $redis, user_type: ->(env) do
  user = current_user(env) # for some current_user method
  user.nil? ? :guest : user.user_type
end, user_key: some_lambda(env)
# Some user model
class User
  # Just for explanation's sake
  def user_type
    if vip?
      :vip
    else
      :normal
    end
  end
end

Does that sound reasonable, or did you have something else in mind?

xevix avatar Nov 25 '15 12:11 xevix

I have added a PR for this (#10), which is slightly different from what's discussed here, but gets to the same result.

ekampp avatar Apr 06 '16 04:04 ekampp