You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

24 lines
734 B

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)
}
}