feat: 新增限流功能 (#718)

* 请求速率限制

* perf: 优化代码

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
This commit is contained in:
xiaozhu
2023-03-21 09:20:27 +08:00
committed by GitHub
parent 47dc009505
commit e02ab1fbad
7 changed files with 42 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ import express from 'express'
import type { ChatContext, ChatMessage } from './chatgpt'
import { chatConfig, chatReplyProcess, currentModel } from './chatgpt'
import { auth } from './middleware/auth'
import { limiter } from './middleware/limiter'
import { isNotEmptyString } from './utils/is'
const app = express()
@@ -17,7 +18,7 @@ app.all('*', (_, res, next) => {
next()
})
router.post('/chat-process', auth, async (req, res) => {
router.post('/chat-process', [auth, limiter], async (req, res) => {
res.setHeader('Content-type', 'application/octet-stream')
try {

View File

@@ -0,0 +1,19 @@
import { rateLimit } from 'express-rate-limit'
import { isNotEmptyString } from '../utils/is'
const MAX_REQUEST_PER_HOUR = process.env.MAX_REQUEST_PER_HOUR
const maxCount = (isNotEmptyString(MAX_REQUEST_PER_HOUR) && !isNaN(Number(MAX_REQUEST_PER_HOUR)))
? parseInt(MAX_REQUEST_PER_HOUR)
: 0 // 0 means unlimited
const limiter = rateLimit({
windowMs: 60 * 60 * 1000, // Maximum number of accesses within an hour
max: maxCount,
statusCode: 200, // 200 means successbut the message is 'Too many request from this IP in 1 hour'
message: async (req, res) => {
res.send({ status: 'Fail', message: 'Too many request from this IP in 1 hour', data: null })
},
})
export { limiter }