Skip to content

Commit

Permalink
docs: add symbol docs
Browse files Browse the repository at this point in the history
  • Loading branch information
YaaY committed Mar 4, 2024
1 parent 9a2a15f commit ef33960
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions throttle.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,51 @@
import { Request, Response, NextFunction } from 'express';

/**
* Options for configuring the rate limiter middleware.
*/
interface RateLimitOptions {
windowMs: number; // Window time in milliseconds
maxRequests: number; // Max number of requests per window per IP
/** Window time in milliseconds for rate limiting. */
windowMs: number;
/** Maximum number of requests allowed per window per IP. */
maxRequests: number;
}

// Simple in-memory store
/**
* Simple in-memory store for tracking request timestamps.
*/
class MemoryStore {
/** Object to store hit timestamps keyed by IP. */
hits: { [key: string]: number[] } = {};

/**
* Increments the count for a given key within the rate limit window.
* @param key The key to increment, typically the IP address.
*/
increment(key: string) {
const now = Date.now();
if (!this.hits[key]) {
this.hits[key] = [];
}
this.hits[key].push(now);
this.hits[key] = this.hits[key].filter(timestamp => now - timestamp <= 60000); // Keep only the timestamps within the last minute
// Remove timestamps outside the current window
this.hits[key] = this.hits[key].filter(timestamp => now - timestamp <= 60000);
}

getCount(key: string) {
/**
* Retrieves the count of hits for a given key.
* @param key The key for which to retrieve the count.
* @returns The number of hits for the key.
*/
getCount(key: string): number {
return this.hits[key] ? this.hits[key].length : 0;
}
}

/**
* Creates a rate limiting middleware function.
* @param options The configuration options for the rate limiter.
* @returns An Express middleware function for rate limiting.
*/
export const rateLimiter = (options: RateLimitOptions) => {
const { windowMs, maxRequests } = options;
const store = new MemoryStore();
Expand Down

0 comments on commit ef33960

Please sign in to comment.