Express-throttle 如何根据函数参数设置 api 调用的成本

Express-throttle how to set cost of api call based on argument for function

我正在使用 express-throttle 来限制每天每个 IP 地址的 api 调用量。我想根据 api 请求中的值在 'options' 数组中设置 'cost' 参数。 (请参阅代码中的评论 'QUESTION')。

因此,请求中的参数决定了 api 调用与最大每日计数器相关的成本(节流器负责处理)。问题是,throttle(options) 是作为 app.post 的参数调用的。所以设置它已经太晚了吗?

我应该怎么做?我在考虑回调,但不确定如何实施。我尝试连续进行 2 次 api 调用,但这可能会导致计时问题。请指教。谢谢

代码:

var throttle = require("express-throttle");
var express = require("express");
var app = express();

var options = {
  "burst": 100,
  "period": "1d",

  // "cost" : 3; <<< This needs to be set to a value from the request.

  "on_throttled": function(req, res, next, bucket) {
      // Set responsemessage when maximum has been reached.
    res.status(503).send("Come back tomorrow.");
  }
};

app.get("/throttletest", throttle(options), (req, res, next) => {

    // QUESTION : I need to set the "cost" parameter to res.body.userBurst.

    res.send("Ok Throttletest");

});

我现在尝试这样设置:

var options = {
  "burst": 100,
  "period": 1d,
  "cost": function(req){
    var amount = req.body.amount;
    return amount;
  },

必须先测试