Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const { shield } = require('graphql-shield');
const { applyMiddleware } = require('graphql-middleware');
const {
createRateLimitDirective,
RedisStore,
getGraphQLRateLimiter,
createRateLimitRule
} = require('graphql-rate-limit');
const redis = require('redis');
// Option 1: Use a directive (applied in the schema below)
const rateLimitDirective = createRateLimitDirective({
identifyContext: context => {
return context.req.ip;
},
store: new RedisStore(redis.createClient())
});
// Option 2: User graphql-shield (applied in the `shield` below)
const rateLimit = createRateLimitRule({
formatError: () => {
return 'Stop doing that so often.';
},
identifyContext: context => {
return context.req.ip;
}
});
const permissions = shield({
Query: {
myId: rateLimit({
max: 2,
// @flow
import { createRateLimitDirective, RedisStore } from 'graphql-rate-limit';
import { getClientIp } from 'request-ip';
import createRedis from 'shared/bull/create-redis';
import ms from 'ms';
export default createRateLimitDirective({
identifyContext: ctx => (ctx.user && ctx.user.id) || getClientIp(ctx.request),
store: new RedisStore(createRedis()),
formatError: ({ fieldName, fieldIdentity, max, window }) =>
`Slow down there partner! You've called '${fieldName}' ${max} times in the past ${ms(
window,
{ long: true }
)}. Relax for a bit and try again later.`,
});