M↓MIGRATION.md
TSindex.ts
TSstore.ts
{}package.json
srcmiddlewarerate-limiterindex.tsrateLimiter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import type { MiddlewareHandler } from '../../types'
import { MemoryStore, type Store } from './store'
/** 滑动窗口:上一窗口按剩余比例计入,边界不再突刺。Sliding window: the last one counted by the share left. */
export const rateLimiter = (options: {
limit: number
windowMs: number
store?: Store
}): MiddlewareHandler => {
const store = options.store ?? new MemoryStore()
return async (c, next) => {
const key = c.req.header('x-forwarded-for') ?? 'anonymous'
const { current, previous, elapsed } = await store.hit(key, options.windowMs)
const weight = 1 - elapsed / options.windowMs
const count = previous * weight + current
c.header('RateLimit', `limit=${options.limit}, remaining=${Math.max(0, options.limit - count)}`)
if (count > options.limit) {
return c.text('Too Many Requests', 429)
}
await next()
}
问题Problems输出Output终端Terminal
➜ hono git:(feat/sliding-window) bun test src/middleware/rate-limiter
bun test v1.2.4
✓ src/middleware/rate-limiter/index.test.ts (9 tests) 21ms
✓ 窗口边界不再突刺no burst at the window’s edge
✓ 存储失效时放行并记日志a failing store lets requests through, logged
9 pass
0 fail
➜ hono git:(feat/sliding-window) ▍