@@ -8,8 +8,9 @@ import { genericConfig } from "common/config.js";
88import { FastifyPluginAsync , FastifyRequest , FastifyReply } from "fastify" ;
99
1010interface RateLimiterOptions {
11- limit ?: number ;
11+ limit ?: number | ( ( request : FastifyRequest ) => number ) ;
1212 duration ?: number ;
13+ rateLimitIdentifier ?: string ;
1314}
1415
1516interface RateLimitParams {
@@ -76,26 +77,32 @@ const rateLimiterPlugin: FastifyPluginAsync<RateLimiterOptions> = async (
7677 fastify ,
7778 options ,
7879) => {
79- const { limit = 10 , duration = 60 } = options ;
80-
80+ const {
81+ limit = 10 ,
82+ duration = 60 ,
83+ rateLimitIdentifier = "api-request" ,
84+ } = options ;
8185 fastify . addHook (
82- "onRequest " ,
86+ "preHandler " ,
8387 async ( request : FastifyRequest , reply : FastifyReply ) => {
8488 const userIdentifier = request . ip ;
85- const rateLimitIdentifier = "api-request" ;
86-
89+ console . log ( request . username ) ;
90+ let computedLimit = limit ;
91+ if ( typeof computedLimit === "function" ) {
92+ computedLimit = computedLimit ( request ) ;
93+ }
8794 const { limited, resetTime, used } = await isAtLimit ( {
8895 ddbClient : fastify . dynamoClient ,
8996 rateLimitIdentifier,
9097 duration,
91- limit,
98+ limit : computedLimit ,
9299 userIdentifier,
93100 } ) ;
94- reply . header ( "X-RateLimit-Limit" , limit . toString ( ) ) ;
101+ reply . header ( "X-RateLimit-Limit" , computedLimit . toString ( ) ) ;
95102 reply . header ( "X-RateLimit-Reset" , resetTime ?. toString ( ) || "0" ) ;
96103 reply . header (
97104 "X-RateLimit-Remaining" ,
98- limited ? 0 : used ? limit - used : limit - 1 ,
105+ limited ? 0 : used ? computedLimit - used : computedLimit - 1 ,
99106 ) ;
100107 if ( limited ) {
101108 const retryAfter = resetTime
0 commit comments