💾 Archived View for iich.space › src › middleware › withThrottling.ts captured on 2022-03-01 at 16:00:07.

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

import { Status } from '@/gemini';
import { Handler } from '@/mission-control';

const DELAY = 10000;

const timestamps = new Map<string, number>();

const withThrottling: Handler = (req, res) => {
  if (req.remote === undefined) {
    res.sendStatus(Status.BAD_REQUEST);
    return res.end();
  }

  if (timestamps.has(req.remote)) {
    const timestamp = timestamps.get(req.remote)!;

    if (timestamp > Date.now() - DELAY) {
      res.sendStatus(Status.SLOW_DOWN);
      return res.end();
    }
  }

  timestamps.set(req.remote, Date.now());
};

export default withThrottling;