limit.ts 686 B

123456789101112131415161718192021
  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 a = await ctx.$redis.get(key)
  14. const limit: number = Number(await ctx.$redis.get(key)) || 0;
  15. if (limit > config.limit.times) {
  16. ctx.throw(403, '请求频次过高');
  17. };
  18. ctx.$redis.setex(key, config.limit.time, String(limit + 1));
  19. await next();
  20. };
  21. };