Created
May 8, 2019 22:56
-
-
Save benawad/8d46151866ee8e1706982ad9686ddb63 to your computer and use it in GitHub Desktop.
This file contains 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> = ( | |
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