The system will add tokens to the bucket at a certain rate. Before processing the request, it needs to obtain a token from the bucket. If there is no token in the bucket, it will return failure.

The general description is as follows:

All requests require an available token before they can be processed; If no token is obtained, the request fails to be returned. Add the token to the bucket at a certain rate based on the traffic limiting size. The bucket sets a maximum placement token limit, and when the bucket is full, newly added tokens are discarded or rejected.

Key points:

  1. Initialize a fixed number of tokens into the token bucket
  2. Initializes and starts a scheduled task that periodically adds tokens to the token bucket
  3. Provides a method to get a token, get a token, subtract one from the token bucket, return failure if the token bucket is empty
class TokenLimiter {
  constructor(limit) {
    this.limit = limitThis.arrayqueue = [] this.init() this.start()} // Initialize the number of tokensinit() {
    console.log(1)
    for (let i = 0; i < this.limit; i++) {
      this.arrayQueue.push('1'}} // Get the tokengetToken() {
    return!!!!! This.arrayqueue.shift ()} // Starts a timer to initialize tokens at a specific timestart() {
    setInterval(() => {
      if(this.arrayqueue.length === 0) {console.log(' token is gone, adding... `) this.init() } },1000) } } module.exports = TokenLimiterCopy the code

So how do we use it in Koa! As follows:

const Koa = require('koa')
const Router = require('koa-router')
const moment = require('moment')

const TokenLimiter = require('./tokenLimiter') const router = new router () const app = new Koa() TokenLimiter = new tokenLimiter (10) const data = require('./data.json')

const limitWrapper = async (ctx, next) => {
  const flag = tokenLimiter.getToken()
  if(! flag) { ctx.response.body ='Network error'
    ctx.response.status = 500
  }
  await next()
}

app.use(limitWrapper)

const leaderboard = async (ctx) => {
  const { type, dateType } = ctx.query
  const filterDate = (date) => moment(moment().subtract(dateType === 'd' ? 0 : 1, dateType).format('YYYY-MM-DD')).isSameOrBefore(date)
  ctx.response.body = data.filter(x => x.type === type && filterDate(x.date))
}

router.get('/leaderboard', leaderboard)

app.use(router.routes())

app.listen(3009)
Copy the code

Above is how to achieve throttling ideas in Koa, after watching it, I think it is ok, give a thumbs up. In addition, I have rich experience in using AWS Lambda. If you are interested in this aspect, you can discuss it