Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save grim-reapper/e6e47919334bca74fb8d0e536b5fcdd0 to your computer and use it in GitHub Desktop.
Save grim-reapper/e6e47919334bca74fb8d0e536b5fcdd0 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