import { Context, Next } from 'koa'; import config from '@config'; export default () => { return async (ctx: Context, next: Next) => { const host: string = ctx.host const isMatch = config.checkHost.find(el => host.match(el)) if (!isMatch) { // 域名不对 ctx.throw(403, '请求出错') } const ip: string = ctx.ip; const key: string = `client_ip_limit_${ip}`; const limit: number = Number(await ctx.$redis.get(key)) || 0; if (limit > config.limit.times) { ctx.throw(403, '请求频次过高'); }; ctx.$redis.setex(key, config.limit.time, String(limit + 1)); await next(); }; };