grape-throttle
grape-throttle copied to clipboard
Different limit based on user group
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?
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?
I have added a PR for this (#10), which is slightly different from what's discussed here, but gets to the same result.