futurestudio / hapi-rate-limitor

A hapi plugin for rate limiting. Simple and easy.
MIT License
43 stars 8 forks source link

Limiting based on JSON request body #231

Closed naftis closed 11 months ago

naftis commented 1 year ago

Hi! We're using Hapi as a GraphQL gateway so our payloads often look like this:

{ "operationName": "getTodos", variables: { .. } }

I'm wondering if there's a way we could rate limit some "operationNames" differently than others. For example { "operationName": "loginWithUsernameAndPassword" } could be limited to 10rq/min, and { "operationName": "logout" } wouldn't need to be rate limited at all.

marcuspoehls commented 1 year ago

@naftis Hi Pyry, you could use the async getIp(request) method to resolve the request identifier manually. The request identifier is then used to rate-limit the request. By default, the package uses the request’s IP address. That’s why the method is using the name 🙂 You could then use your own method like this (using https://github.com/supercharge/request-ip):

const RequestIp = require('@supercharge/request-ip')

await server.register({
  plugin: require(https://github.com/futurestudio/hapi-rate-limitor),
  options: {
    getIp: async (request) => {
      return `${request.payload.operationName}--${RequestIp.getClientIp(request)}`
    }
  }
})

Does this work for you?