2020-04-12 18:27:01 +02:00
|
|
|
import { getGraphQLRateLimiter } from 'graphql-rate-limit';
|
2020-05-19 07:50:16 +02:00
|
|
|
import { logger } from './logger';
|
2020-05-13 07:46:31 +02:00
|
|
|
|
|
|
|
interface RateConfigProps {
|
|
|
|
[key: string]: {
|
|
|
|
max: number;
|
|
|
|
window: string;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2020-05-19 07:50:16 +02:00
|
|
|
export const RateConfig: RateConfigProps = {
|
|
|
|
getMessages: { max: 10, window: '5s' },
|
2020-08-03 16:31:20 +02:00
|
|
|
nodeInfo: { max: 10, window: '5s' },
|
2020-05-19 07:50:16 +02:00
|
|
|
};
|
2020-04-12 18:27:01 +02:00
|
|
|
|
|
|
|
const rateLimiter = getGraphQLRateLimiter({
|
|
|
|
identifyContext: (ctx: string) => ctx,
|
|
|
|
formatError: () => 'Rate Limit Reached',
|
|
|
|
});
|
|
|
|
|
|
|
|
export const requestLimiter = async (rate: string, field: string) => {
|
2020-05-13 07:46:31 +02:00
|
|
|
const { max, window } = RateConfig[field] || { max: 5, window: '5s' };
|
2020-04-12 18:27:01 +02:00
|
|
|
const errorMessage = await rateLimiter(
|
|
|
|
{
|
|
|
|
parent: rate,
|
|
|
|
args: {},
|
|
|
|
context: rate,
|
|
|
|
info: { fieldName: field } as any,
|
|
|
|
},
|
|
|
|
{ max, window }
|
|
|
|
);
|
2020-05-19 07:50:16 +02:00
|
|
|
if (errorMessage) {
|
|
|
|
logger.warn(`Rate limit reached for '${field}' from ip ${rate}`);
|
|
|
|
throw new Error(errorMessage);
|
|
|
|
}
|
2020-04-12 18:27:01 +02:00
|
|
|
};
|