limit.ts 646 B

1234567891011121314151617181920
  1. import { Context, Next } from 'koa';
  2. import config from '@config';
  3. export default () => {
  4. return async (ctx: Context, next: Next) => {
  5. const host: string = ctx.host
  6. const isMatch = config.checkHost.find(el => host.match(el))
  7. if (!isMatch) {
  8. // 域名不对
  9. ctx.throw(403, '请求出错')
  10. }
  11. const ip: string = ctx.ip;
  12. const key: string = `client_ip_limit_${ip}`;
  13. const limit: number = Number(await ctx.$redis.get(key)) || 0;
  14. if (limit > config.limit.times) {
  15. ctx.throw(403, '请求频次过高');
  16. };
  17. ctx.$redis.setex(key, config.limit.time, String(limit + 1));
  18. await next();
  19. };
  20. };