express rate limit redis

Solutions on MaxInterview for express rate limit redis by the best coders in the world

showing results for - "express rate limit redis"
Cristina
27 Oct 2016
1import { Request, Response, NextFunction } from 'express'
2import IORedis from 'ioredis'
3import ip from 'request-ip'
4
5let io = new IORedis({
6	host: process.env.REDIS_HOST || 'localhost',
7	port: parseInt(process.env.REDIS_PORT || '')
8})
9
10export async function rateLimiterById(req: Request, res: Response, next: NextFunction): Promise<any> {
11	// store id to redis
12	await io.set(`redis-id:${req.payload.uid}`, req.payload.uid)
13	// get request by id
14	const getId = await io.get(`redis-id:${req.payload.uid}`)
15	// counter count request
16	const maxCounterRequest = await io.incrby(`counter-id:${req.payload.uid}`, 1)
17
18	if (getId === req.payload.uid && maxCounterRequest <= 50) {
19		await io.expire(`counter-id:${req.payload.uid}`, 10)
20	} else {
21		await io.del(`redis-id:${req.payload.uid}`)
22		return res.status(429).json({
23			status: 'ERROR TO MANY REQUEST',
24			code: 'AX2AC5R',
25			message: 'cannot access this endpoint, after 10 second is over'
26		})
27	}
28
29	next()
30}
31
32export async function rateLimiterByIp(req: Response, res: Response, next: NextFunction): Promise<any> {
33	const getIp = ip.getClientIp(req)
34	// store id to redis
35	await io.set(`redis-ip:${getIp}`, `${getIp}`)
36	// get request by id
37	const getStoreIp = await io.get(`redis-ip:${getIp}`)
38	// counter count request
39	const maxCounterRequest = await io.incrby(`counter-ip:${getIp}`, 1)
40
41	if (getStoreIp === getIp && maxCounterRequest <= 50) {
42		await io.expire(`counter-ip:${getIp}`, 10)
43	} else {
44		await io.del(`redis-ip:${getIp}`)
45		return res.status(429).json({
46			status: 'ERROR TO MANY REQUEST',
47			code: 'AX2AC5R',
48			message: 'cannot access this endpoint, after 10 second is over'
49		})
50	}
51
52	next()
53}