mirror of
				https://gitlab.com/comunic/comunicapiv2
				synced 2025-11-03 19:14:03 +00:00 
			
		
		
		
	Automatically clean up old entries
This commit is contained in:
		@@ -8,6 +8,7 @@
 | 
			
		||||
 */
 | 
			
		||||
 | 
			
		||||
import { time } from "../utils/DateUtils";
 | 
			
		||||
import { removeWhere } from "../utils/ArrayUtils";
 | 
			
		||||
 | 
			
		||||
// Different supported actions
 | 
			
		||||
export enum Action {
 | 
			
		||||
@@ -18,7 +19,7 @@ export enum Action {
 | 
			
		||||
/**
 | 
			
		||||
 * The duration entries will be kept in the table
 | 
			
		||||
 */
 | 
			
		||||
const MAX_TIME = 20;//3600; // 1 hour
 | 
			
		||||
const MAX_TIME = 3600; // 1 hour
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Information about a specific IP & action
 | 
			
		||||
@@ -44,6 +45,10 @@ export class APILimitHelper {
 | 
			
		||||
	 * @param action Target action
 | 
			
		||||
	 */
 | 
			
		||||
	private static FindEntry(ip: string, action: Action) : CountInfo {
 | 
			
		||||
 | 
			
		||||
		// Remove old entries
 | 
			
		||||
		removeWhere(list, (entry) => entry.time + MAX_TIME < time());
 | 
			
		||||
		
 | 
			
		||||
		return list.find((f) => f.ip == ip && f.action == action);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
@@ -77,7 +82,7 @@ export class APILimitHelper {
 | 
			
		||||
	 */
 | 
			
		||||
	public static async Count(ip: string, action: Action) : Promise<number> {
 | 
			
		||||
		const entry = this.FindEntry(ip, action);
 | 
			
		||||
		console.log(entry)
 | 
			
		||||
		
 | 
			
		||||
		return entry == undefined ? 0 : entry.count;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
@@ -22,3 +22,19 @@ export function findKey(object: Object, value: any): string {
 | 
			
		||||
 | 
			
		||||
	return null;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Remove all the entries of an array that meets a certain condition
 | 
			
		||||
 * 
 | 
			
		||||
 * @param array Input array
 | 
			
		||||
 * @param callback Callback function to call on each element
 | 
			
		||||
 * of the array
 | 
			
		||||
 */
 | 
			
		||||
export function removeWhere<T>(array: Array<T>, callback: (el: T) => boolean) {
 | 
			
		||||
    var i = array.length;
 | 
			
		||||
    while (i--) {
 | 
			
		||||
        if (callback(array[i])) {
 | 
			
		||||
            array.splice(i, 1);
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
};
 | 
			
		||||
		Reference in New Issue
	
	Block a user