node.js - 公共模块在路由内的代码之前执行?
问题描述
我在 nodejs 中创建了一个公共模块,并且我在路由中使用该公共模块,我想向所有用户发送通知现在问题是当我调用路由时,第一个公共模块被执行,然后执行路由内的代码,但是我想要的是第一条路线代码应该执行然后公共模块应该执行。
这是路线,noti 是通用模块
router.post('/', session, noti, async (req, res) => {
const dt = dateTime.create();
const formatted1 = dt.format('Y-m-d H:M:S');
try {
const str = req.body.providerId;
const data = str.split("|");
const id = data[0];
const name = data[1];
const date = req.body.resultDate;
const digit = req.body.winningDigit;
const exist = await ABgameResult.findOne({ providerId: id,resultDate: date,session: req.body.session });
if (!exist) {
const details = new ABgameResult({
providerId: id,
providerName: name,
resultDate: date,
winningDigit: digit,
status: 0
});
const savedGames = await details.save();
const update1 = await ABgamesProvider.updateOne(
{_id : id },
{ $set: { providerResult: digit, modifiedAt: formatted1,resultStatus : 1 } });
//resultStatus : 1 i.e; result is declared
const Resultid = savedGames._id;
const listData = {
providerId : id,
resultDate : date,
status: 0,
winningDigit: digit,
resultId: Resultid,
providerName: name
}
return res.json({
status : 1,
message : "Success",
data: listData
});
}
else {
const data = 'Details Already Filled For : '+ name +', Session : ' + req.body.session + ', Date: ' + req.body.resultDate;
res.json(data);
}
}catch (e) {
console.log(e);
res.json(e);
}
});
现在我想要的是当执行路线中的其他部分时noti模块不应该被执行我只想在部分代码中执行它
这是noti的模块
module.exports = async function ( req, res,next) {
try
{
const token = await user.find({ banned : 1, andarBaharNotification: true }, {firebaseId : 1});
let userToken = [];
for(index in token){
userToken.push(token[index].firebaseId);
}
const digit = req.body.winningDigit;
const str = req.body.providerId;
const data = str.split("|");
const name = data[1];
var message = new gcm.Message({
priority: 'high',
data: {
title: " ("+name+")",
icon: "ic_launcher",
body: digit
}
});
sender.send(message, { registrationTokens: userToken }, function (err, response) {
if (err) console.error('error => ' ,err);
else console.log('response=> ',response);
});
next()
}
catch (e) {
console.log(e);
res.status(400).json({
status: 0,
message: 'Something Happpend',
error: e
});
}
};
解决方案
我想你想这样做!
const noti = require('./noti'); // importing noti
router.post('/', session, async (req, res) => {
// DO YOUR STUFF
noti(req, res);
});
next()
从通知模块中删除。
推荐阅读
- javascript - 当用户在输入字段中输入值时,使用 javascript 格式化输入值
- vue.js - 计算属性的返回值在模板中使用时不会改变(没有组合 API 的 Vue3)
- matlab - 如何将unnest单元阵列更改为排队的阵型?
- javascript - 表格没有在 jQuery 中动态附加
- azure - Azure 内部负载均衡器能否拥有属于 VNET 中不同子网的后端?
- sql - 执行 INSERT INTO 与使用 MERGE INTO 之间的区别
- mysql - MySQL慢查询连接两个表,每个表都有全文条件
- python - Python字节增量
- prolog - Prolog 停留在一个复杂的谓词上
- r - 安装 R 包“验证”退出并出现错误