@trpc-limiter/core
Version:
The core of tRPC limiter.
47 lines (43 loc) • 2.94 kB
TypeScript
import { RootConfig, AnyRootTypes, MiddlewareFunction } from '@trpc/server/unstable-core-do-not-import';
type AnyRootConfig = {
_config: RootConfig<AnyRootTypes>;
};
type BaseOpts<TRoot extends AnyRootConfig, Res> = {
/**
* Time frame in milliseconds how long to keep track of requests
* @default 60000 (1 minute)
*/
windowMs?: number;
/**
* The number of requests allowed per `windowMs`.
* @default 5
**/
max?: number;
/**
* The response body to send when a request is blocked.
* @default 'Too many requests, please try again later.'
**/
message?: string | ILimiterCallback<TRoot, Res>;
/**
* This will be called when a request is blocked.
**/
onLimit?: ILimiterCallback<TRoot, Res, void>;
/**
* Function to generate a fingerprint for a request based on tRPC context.
* @required
**/
fingerprint: (ctx: TRoot['_config']['$types']['ctx'], input: any) => string | Promise<string>;
};
type TRPCRateLimitOptions<TRoot extends AnyRootConfig, Res, A = null> = A extends null ? BaseOpts<TRoot, Res> : A & BaseOpts<TRoot, Res>;
type ILimiterCallback<TRoot extends AnyRootConfig, Res, T = string> = (info: Res, ctx: TRoot['_config']['$types']['ctx'], fingerprint: string) => T | Promise<T>;
type ILimiterAdapter<Store extends IStoreCallback<A>, Res, A = null> = {
store: Store;
isBlocked: (store: ReturnType<Store>, fingerprint: string, opts: Required<TRPCRateLimitOptions<AnyRootConfig, Store>>) => Promise<InferResCallback<Res> | null> | InferResCallback<Res> | null;
};
type InferResCallback<Res> = NonNullable<Res extends Promise<infer R2> ? R2 : Res>;
type IStoreCallback<A = null> = (opts: Required<TRPCRateLimitOptions<AnyRootConfig, any, A>>) => any;
type MwFn<TRoot extends AnyRootConfig> = MiddlewareFunction<TRoot['_config']['$types']['ctx'], TRoot['_config']['$types']['meta'], TRoot['_config']['$types']['ctx'], TRoot['_config']['$types']['ctx'], unknown>;
declare const defineTRPCLimiter: <Store extends IStoreCallback<A>, Res, A = null>(adapter: ILimiterAdapter<Store, Res, A>, getDefaultOptions?: ((currentState: Required<TRPCRateLimitOptions<AnyRootConfig, any, A>>) => Required<A>) | undefined) => <TRoot extends AnyRootConfig>(opts: TRPCRateLimitOptions<TRoot, Res, A>) => MwFn<TRoot>;
declare const defineLimiterWithProps: <T, Res, Store extends IStoreCallback<T> = IStoreCallback<T>>(adapter: ILimiterAdapter<Store, Res, T>, getDefaultOptions: (currentState: Required<TRPCRateLimitOptions<AnyRootConfig, any, T>>) => Required<T>) => <TRoot extends AnyRootConfig>(opts: TRPCRateLimitOptions<TRoot, Res, T>) => MwFn<AnyRootConfig>;
declare const defaultFingerPrint: (req: Request | Record<any, any>) => any;
export { AnyRootConfig, BaseOpts, ILimiterAdapter, ILimiterCallback, IStoreCallback, InferResCallback, MwFn, TRPCRateLimitOptions, defaultFingerPrint, defineLimiterWithProps, defineTRPCLimiter };