rhinobase / hono-rate-limiter

Rate Limit middleware for Hono Server
https://hono-rate-limiter.vercel.app
MIT License
281 stars 13 forks source link

Wrong types for Deno #28

Open hpandelo opened 1 month ago

hpandelo commented 1 month ago

I'm facing many issue with the types using Deno + jsr:@hono/hono + npm:hono-rate-limiter The main one is the following:

The code is pretty new, without so many personal things yet: It was originally inside the RateLimitMiddleware class

import { Context, Hono } from "hono";
import { HTTP_STATUS_CODES } from '@utils/http.constants.ts';
import { AuthMiddleware, ErrorMiddleware, RateLimitMiddleware } from '@src/middlewares/index.ts';
import { rateLimiter } from 'npm:hono-rate-limiter';

const app = new Hono();

// Made following the examples provided
const limiter = rateLimiter({
  windowMs: Deno.env.has('RATE_LIMIT_WINDOW_MS')
    ? +Deno.env.get('RATE_LIMIT_WINDOW_MS')!
    : 60_000, // 1 minute
  limit: Deno.env.has('RATE_LIMIT_MAX_REQUESTS')
    ? +Deno.env.get('RATE_LIMIT_MAX_REQUESTS')!
    : 10,
  standardHeaders: 'draft-6',
  keyGenerator: (c) => c.req.header('x-forwarded-for') ?? '', // No types
});

// Internal Middlewares
app.onError(ErrorMiddleware.handler);
app.use(limiter);

// ... our routes here

export app;

Issue: image

The other one is if I also try to type the keyGenerator it breaks too: keyGenerator: (c: Context) => c.req.header('x-forwarded-for') ?? '',

image

Aaaannnd... By typing the return of rateLimiter, it breaks like this one: image

MathurAditya724 commented 1 month ago

I think this sould resolve your issue -

app.use(rateLimiter({
  windowMs: Deno.env.has('RATE_LIMIT_WINDOW_MS')
    ? +Deno.env.get('RATE_LIMIT_WINDOW_MS')!
    : 60_000, // 1 minute
  limit: Deno.env.has('RATE_LIMIT_MAX_REQUESTS')
    ? +Deno.env.get('RATE_LIMIT_MAX_REQUESTS')!
    : 10,
  standardHeaders: 'draft-6',
  keyGenerator: (c) => c.req.header('x-forwarded-for') ?? '', // No types
}))

You need to provide the E, P and I, generic types in the limiter.