Skip to content

Commit a6fde7d

Browse files
committed
fix: add convertPeriodToSeconds utility function and refactor RateLimiter to use it
1 parent 62d130e commit a6fde7d

2 files changed

Lines changed: 17 additions & 14 deletions

File tree

adminforth/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import SQLiteConnector from './dataConnectors/sqlite.js';
66
import CodeInjector from './modules/codeInjector.js';
77
import ExpressServer from './servers/express.js';
88
// import FastifyServer from './servers/fastify.js';
9-
import { ADMINFORTH_VERSION, listify, suggestIfTypo, RateLimiter, RAMLock, getClientIp, isProbablyUUIDColumn } from './modules/utils.js';
9+
import { ADMINFORTH_VERSION, listify, suggestIfTypo, RateLimiter, RAMLock, getClientIp, isProbablyUUIDColumn, convertPeriodToSeconds } from './modules/utils.js';
1010
import {
1111
type AdminForthConfig,
1212
type IAdminForth,
@@ -48,7 +48,7 @@ export * from './types/adapters/index.js';
4848
export * from './modules/filtersTools.js';
4949
export { interpretResource };
5050
export { AdminForthPlugin };
51-
export { suggestIfTypo, RateLimiter, RAMLock, getClientIp };
51+
export { suggestIfTypo, RateLimiter, RAMLock, getClientIp, convertPeriodToSeconds };
5252

5353

5454
class AdminForth implements IAdminForth {

adminforth/modules/utils.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,20 @@ export function md5hash(str:string) {
381381
return crypto.createHash('md5').update(str).digest('hex');
382382
}
383383

384+
export function convertPeriodToSeconds(period: string): number {
385+
const periodChar = period.slice(-1);
386+
const duration = parseInt(period.slice(0, -1));
387+
if (periodChar === 's') {
388+
return duration;
389+
} else if (periodChar === 'm') {
390+
return duration * 60;
391+
} else if (periodChar === 'h') {
392+
return duration * 60 * 60;
393+
} else if (periodChar === 'd') {
394+
return duration * 60 * 60 * 24;
395+
}
396+
throw new Error(`Invalid period: ${period}`);
397+
}
384398
export class RateLimiter {
385399
// constructor, accepts string like 10/10m, or 20/10s, or 30/1d
386400

@@ -394,18 +408,7 @@ export class RateLimiter {
394408
}
395409

396410

397-
const period = rate.slice(-1);
398-
const duration = parseInt(rate.slice(0, -1));
399-
if (period === 's') {
400-
return duration;
401-
} else if (period === 'm') {
402-
return duration * 60;
403-
} else if (period === 'h') {
404-
return duration * 60 * 60;
405-
} else if (period === 'd') {
406-
return duration * 60 * 60 * 24;
407-
}
408-
throw new Error(`Invalid rate duration period: ${period}`);
411+
return convertPeriodToSeconds(rate);
409412
}
410413

411414

0 commit comments

Comments
 (0)