将路由处理程序委托给NodeJS+Express中的其他模块

Delegate route handlers to other modules in NodeJS+Express

本文关键字:NodeJS+Express 其他 模块 路由 处理 程序      更新时间:2023-09-26

我一直在努力避免routes.js文件中的开销。

给你:

module.exports = function(app, db) {
app.get('/', function(req, res) {
    res.render('index')
});
app.get('/contact-us', function(req, res) {
    var col = db.collection('contacts');
    var transporter = nodemailer.createTransport({
        service: 'Gmail',
        auth: {
            user: 'gmail.user@gmail.com',
            pass: 'userpass'
        }
    });
});
});
}

正如您所看到的,仅仅通过实例化mongo集合和邮件传输程序,这已经被业务逻辑淹没了。我找不到任何关于如何将此逻辑委托给外部模块的材料,例如sendmail.js、savetomongo.js等

有什么建议吗?

我做了一些修改。我已经根据您的要求进行了更新。你需要根据自己的实际需要来做。

var sendmail = require('./sendmail.js');
var savetomongo = require('./savetomongo.js');
module.exports = function(app, db) {
    app.get('/', function(req, res) {
        res.render('index')
    });
    app.get('/contact-us', function(req, res) {
        var col = db.collection('contacts');
        var document = {'id': 'xyz'};
        savetomongo.save(col, document, function(error, is_save) {
            if (error) {
                //handle error
            } else {
                // next()
                sendmail.sendEmail('DUMMY <from@xyz.com>', 'to@xyz.com', 'TestEmail', 'Only for testing purpose', function(error, isSend) {
                    if (error) {
                        //handle error
                    } else {
                        // next() 
                        //res.render('index')
                    }
                });
            }
        });
    });
}

//sendmail.js

module.exports = {
    sendEmail: function(fromEmailFormatted, toEmail, subject, message, fn) {
        var mailOptions = {
            from: fromEmailFormatted, // sender address
            to: toEmail, // list of receivers
            subject: subject, // Subject line
            html: message // html body
        };
        var transporter = nodemailer.createTransport({
            service: 'Gmail',
            auth: {
                user: 'gmail.user@gmail.com',
                pass: 'userpass'
            }
        });
        // send mail with defined transport object
        transporter.sendMail(mailOptions, function(error, info) {
            if (error) {
                return fn(error);
            } else {
                return fn(null, true);
            }
        });
    }
}

//savetomongo.js

module.exports = {
    save: function(col, data, fn) {
        col.insert(data, {w: 1}, function(err, records) {
            if (err) {
                return fn(err);
            } else {
                return fn(null, records);
            }
        });
    }
}