Skip to content

Instantly share code, notes, and snippets.

@benawad
Created May 8, 2019 22:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benawad/8d46151866ee8e1706982ad9686ddb63 to your computer and use it in GitHub Desktop.
Save benawad/8d46151866ee8e1706982ad9686ddb63 to your computer and use it in GitHub Desktop.
import { MiddlewareFn } from "type-graphql";
import { redis } from "./redis";
import { MyContext } from "./types/MyContext";
const ONE_DAY = 60 * 60 * 24;
export const rateLimit: (limit?: number) => MiddlewareFn<MyContext> = (
limitForAnonUser = 50,
limitForUser = 100
) => async ({ context: { req }, info }, next) => {
const isAnon = !req.session!.userId;
const key = `rate-limit:${info.fieldName}:${
isAnon ? req.ip : req.session!.userId
}`;
const current = await redis.incr(key);
if (
(isAnon && current > limitForAnonUser) ||
(!isAnon && current > limitForUser)
) {
throw new Error("you're doing that too much");
} else if (current === 1) {
await redis.expire(key, ONE_DAY);
}
return next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment