-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrpcRateLimiter.ts
More file actions
43 lines (36 loc) · 1 KB
/
trpcRateLimiter.ts
File metadata and controls
43 lines (36 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { defineTRPCLimiter } from '@trpc-limiter/core';
type HitInfo = {
totalHits: number;
resetTime: Date;
};
class MemoryStore {
private hits: Map<string, HitInfo>;
constructor(private windowMs: number) {
this.hits = new Map();
}
async increment(fingerPrint: string): Promise<HitInfo> {
const now = Date.now();
const existing = this.hits.get(fingerPrint);
if (!existing || now > existing.resetTime.getTime()) {
const fresh = {
totalHits: 1,
resetTime: new Date(now + this.windowMs * 10)
};
this.hits.set(fingerPrint, fresh);
return fresh;
}
existing.totalHits += 1;
this.hits.set(fingerPrint, existing);
return existing;
}
}
export const createTRPCStoreLimiter = defineTRPCLimiter({
store: opts => new MemoryStore(opts.windowMs),
isBlocked: async (store, fingerPrint, opts) => {
const { totalHits, resetTime } = await store.increment(fingerPrint);
if (totalHits > opts.max) {
return Math.ceil((resetTime.getTime() - Date.now()) / 1000);
}
return null;
}
});