Ota*_*der 5 javascript node.js
我正在创建一个调用 API 并将其响应存储在数据库中的 CronJob:
const CronJob = require("cron").CronJob;
const btc_price_ticker = require("../../controllers/BtcExchange/Ticker");
const currency = require("../../controllers/Currencies/CurrenciesController");
module.exports = new CronJob("* * * * * *", async function() {
const {
ticker: { sell }
} = await btc_price_ticker.getBtcPrice();
currency
.update({
params: {
id: "5cbdf078f5bcec257fcec792"
},
body: {
exchange_rate: sell,
lastUpdate: Date.now()
}
})
.catch(error => console.log(error));
});
Run Code Online (Sandbox Code Playgroud)
它工作正常,但是我收到一个 TypeError: Cannot read property 'json' of undefined
我使用相同的函数来更新我在更新 API 时使用的数据库:
module.exports = {
async update(req, res) {
const currency = await Currency.findByIdAndUpdate(req.params.id, req.body, {
new: true
});
return res.json(currency);
}
};
Run Code Online (Sandbox Code Playgroud)
这 TypeError在发生return res.json(currency),而且只发生时,它被称为的cronjob。当我通过 API 输入新信息时,它没有显示任何错误。
我认为这是因为当我调用函数时 CronJob,我只是传递了reqby 参数,但我不知道如何解决它。我应该做些什么?
提前致谢!
有一句名言说,通过添加另一层间接层,您几乎可以解决 CS 中的任何问题。这是其中之一:
而不是将您的模块声明为:
module.exports = {
async update(req, res) {
const currency = await Currency.findByIdAndUpdate(req.params.id, req.body, {
new: true
});
return res.json(currency);
}
};
Run Code Online (Sandbox Code Playgroud)
将逻辑与路由逻辑分开:
module.exports = {
async getCurrency(id, params) {
const currency = await Currency.findByIdAndUpdate(id, params, {
new: true
});
return currency;
}
async update(req, res) {
const currency = await getCurrency(req.params.id, req.body);
return res.json(currency);
}
};
Run Code Online (Sandbox Code Playgroud)
现在路由可以调用了update(),cron-job也可以getCurrency()直接调用了。
| 归档时间: |
|
| 查看次数: |
6505 次 |
| 最近记录: |