import {Cache, http, HTTPStatus, Inject, Injectable, Middleware} from '@extollo/lib'

/**
 * RateLimit Middleware
 * --------------------------------------------
 * Limits a route to one request / 30 seconds / IP address.
 */
@Injectable()
export class RateLimit extends Middleware {
    @Inject()
    protected readonly cache!: Cache

    public async apply() {
        const slug = `extollo__rate_limit__${this.request.path}__${this.request.address.address}`
        if ( await this.cache.has(slug) ) {
            return http(HTTPStatus.TOO_MANY_REQUESTS)
        }

        const date = new Date()
        date.setSeconds(date.getSeconds() + 30)  // one request / 30 seconds
        await this.cache.put(slug, slug, date)
    }
}
