limit.ts 819 B

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