pre_process.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // 请求预处理
  2. // 在请求被处理之前执行的函数
  3. //
  4. // @param {Object} ctx - 请求上下文对象
  5. // @returns {Object|undefined} - 返回修改后的请求对象或 undefined
  6. //
  7. // 参考: [JS Rt](./middleware/js_rt.go) 里的 `JSContext`
  8. function preProcessRequest(ctx) {
  9. // 例子:基于数据库的速率限制
  10. // if (ctx.url.includes("/v1/chat/completions")) {
  11. // try {
  12. // // Check recent requests from this IP
  13. // var recentRequests = db.Query(
  14. // "SELECT COUNT(*) as count FROM logs WHERE created_at > ? AND ip = ?",
  15. // Math.floor(Date.now() / 1000) - 60, // last minute
  16. // ctx.remoteIP
  17. // );
  18. // if (recentRequests && recentRequests.length > 0 && recentRequests[0].count > 10) {
  19. // console.log("速率限制 IP:", ctx.RemoteIP);
  20. // return {
  21. // block: true,
  22. // statusCode: 429,
  23. // message: "超过速率限制"
  24. // };
  25. // }
  26. // } catch (e) {
  27. // console.error("Ratelimit 数据库错误:", e);
  28. // }
  29. // }
  30. // 例子:修改请求
  31. if (ctx.URL.includes("/v1/chat/completions")) {
  32. try {
  33. var bodyObj = ctx.Body;
  34. let firstMsg = {
  35. role: "user",
  36. content: "今天天气怎么样"
  37. };
  38. bodyObj.messages[0] = firstMsg;
  39. console.log("Modified first message:", JSON.stringify(firstMsg));
  40. console.log("Modified body:", JSON.stringify(bodyObj));
  41. return {
  42. body: bodyObj,
  43. headers: {
  44. ...ctx.Headers,
  45. "X-Modified-Body": "true"
  46. }
  47. };
  48. } catch (e) {
  49. console.error("Failed to modify request body:", {
  50. message: e.message,
  51. stack: e.stack,
  52. bodyType: typeof ctx.Body,
  53. url: ctx.URL
  54. });
  55. }
  56. }
  57. return undefined; // 跳过处理,继续执行下一个中间件或路由
  58. }