【发布时间】:2020-03-10 09:37:12
【问题描述】:
我在 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的模块
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
});
}
};
【问题讨论】:
-
首先你的router.post右括号在哪里?
-
在路线的尽头
标签: node.js mongodb mongoose ejs