Skip to content

Instantly share code, notes, and snippets.

@benawad
Created May 8, 2019 22:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benawad/71717c5abe5594ce9f7df142dff9e564 to your computer and use it in GitHub Desktop.
Save benawad/71717c5abe5594ce9f7df142dff9e564 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> = (
limit = 50
) => async ({ context: { req }, info }, next) => {
const key = `rate-limit:${info.fieldName}:${req.ip}`;
const current = await redis.incr(key);
if (current > limit) {
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