如何通过节点访问路由器JavaScript文件中的功能



我正在处理不是我的网络应用程序,现在我必须发送一百封电子邮件。

不幸的是,该代码没有记录且编写不太好,这意味着我必须去测试它以发现我能够做的事情,而我不做什么。但是我不知道如何通过节点访问代码上的此功能。实际上可以这样做吗?这是代码:

  router.post('/aprovadosemail', miPermiso("3"), (req, res) => {
  var templatesDir = path.resolve(__dirname, '..', 'templates');
  var emailTemplates = require('email-templates');
  // Prepare nodemailer transport object
  emailTemplates(templatesDir, function(err, template) {
    if (err) {
      console.log(err);
    } else {
      var users = [];
      projetoSchema.find({"aprovado":true, "categoria":"Fundamental II (6º ao 9º anos)"}, function (err, docs) {
        if (err) throw err;
        //console.log(docs);
        docs.forEach(function(usr) {
          let url = "http://www.movaci.com.b/projetos/confirma/"+usr._id+"/2456";
          let url2 = "http://www.movaci.com.br/projetos/confirma/"+usr._id+"/9877";
          users.push({'email': usr.email, 'projeto': usr.nomeProjeto, 'url': url, 'url2': url2});
        });
        for (var i = 0; i < users.length; i++) {
          console.log(users[i]);
        }
        const transporter = nodemailer.createTransport(smtpTransport({
          host: 'smtp.zoho.com',
          port: 587,
          auth: {
            user: "generic@mail.com",
            pass: "genericpassword"
          },
          getSocket: true
        }));
        var Render = function(locals) {
          this.locals = locals;
          this.send = function(err, html, text) {
            if (err) {
              console.log(err);
            } else {
              transporter.sendMail({
                from: 'no-reply4@movaci.com.br',
                to: locals.email,
                subject: 'MOVACI - Projeto aprovado!',
                html: html,
                text: text
              }, function(err, responseStatus) {
                if (err) {
                  console.log(err);
                } else {
                  console.log(responseStatus.message);
                }
              });
            }
          };
          this.batch = function(batch) {
            batch(this.locals, templatesDir, this.send);
          };
        };
        // Load the template and send the emails
        template('rateada', true, function(err, batch) {
          for(var user in users) {
            var render = new Render(users[user]);
            render.batch(batch);
          };
        });
        res.send('ok');
      });
    };
  });
});

似乎以前的开发人员不知道email-templates软件包(至少没有读取其工作原理)。

因此,实际上它具有发送方法,您可以从email-templates创建电子邮件对象并传递必要的默认值,然后通过传递动态零件来调用IT的.send方法 - 它只是简单地合并在发送参数中传递的其他参数,使用邮件,使用在返回的诺言内的nodemailer。

如果对您来说很有趣 - 读取它的源代码:https://github.com/niftylettuce/email-templates/blob/master/master/index.js



我试图使用承诺简化模块化零件。

我没有调试它,但是您可以检查我的解决方案并根据需要进行修复。

有2个文件(分别从处理程序进行路由,它可能具有可能发生冲突等的变量):

1)methods/users/aprovadosEmail.js

const
    Email = require('email-templates'),
const
    emailTemplatesDir = path.resolve(__dirname + '/../../templates'),
    smtpTransportConfig = {
        host: 'smtp.zoho.com',
        port: 587,
        secure: false,
        auth: {
            user: "no-reply4@movaci.com.br",
            pass: "some-password-here"
        }
    },
    createEmail = (template, subject) => {
        return new Email({
            views: {
                root: emailTemplatesDir,
            },
            transport: smtpTransportConfig,
            template,
            message: {
                from: 'no-reply4@movaci.com.br',
                subject
            }
        });
    },
    getApprovedUsers = () => {
        return new Promise((resolve, reject) => {
            const criteria = {
                aprovado: true, 
                categoria:"Fundamental II (6º ao 9º anos)"
            };
            projetoSchema.find(
                criteria,
                (error, docs) => {
                    if(error) return reject(error);
                    const users = docs.map(doc => {
                        return {
                            email: doc.email,
                            projeto: doc.nomeProjeto,
                            url: "http://www.movaci.com.b/projetos/confirma/"+doc._id+"/2456",
                            url2: "http://www.movaci.com.br/projetos/confirma/"+doc._id+"/9877"
                        };
                    });
                    resolve(users);
                });
        });
    },
    sendMailToUser = (mail, user) => {
        return mail.send({
            message: {
                to: user.email
            },
            locals: user
        });
    },
    broadcastMailToUsers = (mail, users) => {
        return Promise
                .all(
                    users
                        .map(user => sendMailToUser(mail, user))
                );
    };
module.exports = (req, res) => {
    const mail = createEmail('rateada', 'MOVACI - Projeto aprovado!'); // mail object
    getApprovedUsers()
        .then(users => broadcastMailToUsers(mail, users))
        .then(result => {
            console.log('Result of broadcast:', result);
            res.send('ok');
        })
        .catch(error => {
            res.status(500).send(error);
        });
};

2)当前路由文件,其中使用模块文件的路由部分:

router.post(
    '/aprovadosemail',
    miPermiso("3"), 
    require(__dirname+'/../methods/users/aprovadosEmail')
);

最新更新