Created
May 8, 2019 22:57
-
-
Save benawad/71717c5abe5594ce9f7df142dff9e564 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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