import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';
import { RateLimiterMemory } from "rate-limiter-flexible";
@Middleware()
export class RateLimitMiddleware implements IMiddleware<Context, NextFunction> {
    /**
     * 限流实例
     */
    private limiterIns:RateLimiterMemory;
    /**
     * 必须实现
     * @returns
     */
    resolve() {
        return async (ctx: Context, next: NextFunction) => {
            try {
                if(!this.limiterIns) {
                    const config = ctx.app.getConfig('limiter');
                    this.limiterIns = new RateLimiterMemory(config);
                }
                await this.limiterIns.consume(ctx.ip);
            } catch(err:any) {
                ctx.status = 429;
                ctx.body = 'Too Many Requests';
                return;
            }
            await next();
        };
    }
    /**
     * 中间件名称
     * @returns
     */
    static getName(): string {
        return 'apilimit';
    }
}
