pg-promise-无法解决多个查询

时间:2018-09-05 23:32:40

标签: postgresql express pg-promise

我正在创建一个批量邮件程序,该邮件程序使公司可以将电子邮件模板发送到包含X个订户的特定计划。

但是,当使用pg-promise时,我无法弄清楚如何遍历包含一个或多个唯一计划名称的数组,然后将其用作随后的查询的查询参数以收集单个结果数组。 后续查询在Express发送回指定的错误消息之前无法解决。

例如:

const selectedTemplate = await db.oneOrNone("SELECT * FROM templates WHERE userid=$1 and uniqueTemplateName=$2", [req.session.id, req.body.uniquetemplatename])

返回JSON对象...

{ ...
  plans : [ 'Unique Plan 1', 'Unique Plan 2', 'Unique Plan 3'...],
  ...
}

然后,我想遍历此plans数组以收集一些订户电子邮件。由于selectedTemplate的plans数组可以包含一个或多个“唯一计划”,因此我试图找出如何使此查询起作用:

let subscriberEmails = [];

await each(selectedTemplate.plans, async plan => {
  const emails = await db.any("SELECT email FROM subscribers WHERE userid=$1 AND planName=$2", [req.session.id, plan])          
  each(emails, ({email}) => subscriberEmails.push(email))           
  console.log('Found emails: ', subscriberEmails);
})

console.log('Selected emails: ', subscriberEmails);
res.status(500).json({ message: "Route not configured yet" })

我遇到的问题是Express不在等待pg-promise解决。因此,它触发了我的500台服务器“尚未配置路由”消息,然后< / strong>解决查询:

14:48:33 SELECT * FROM templates WHERE userid='12345' and uniqueTemplateName='example-unique-template'

        selectedTemplate: anonymous {
          id: '84efa448-b149-11e8-a7fd-3b9e4e9e5ece',
          key: 9,
          userid: '12345',
          status: 'active',
          fromsender: 'example@helpdesk.com',
          subject: 'Thank you for using our services!',
          templatename: 'Example Unique Template',
          uniquetemplatename: 'example-unique-template',
          message: '<h3>This is a test!</h3>',
          plans: [ 'Unique Plan 1', 'Unique Plan 2' ] 
        }

        Selected emails: []

POST /api/messages/create 500 28 - 34.125 ms

14:48:33 SELECT email FROM subscribers WHERE userid='12345' AND planName='Unique Plan 1'

        Found emails:  [ 
         'betatester19@example.com',
         'betatester20@example.com',
         'betatester21@example.com'
        ]

14:48:34 SELECT email FROM subscribers WHERE userid='12345' AND planName='Unique Plan 2'

        Found emails:  [ 
         'betatester19@example.com',
         'betatester20@example.com',
         'betatester21@example.com',
         'betatester1@example.com',
         'betatester2@example.com',
         'betatester3@example.com',
         'betatester4@example.com',
         'betatester5@example.com',
         'betatester6@example.com',
         'betatester7@example.com',
         'betatester8@example.com',
         'betatester9@example.com',
         'betatester10@example.com',
         'betatester11@example.com',
         'betatester12@example.com',
         'betatester13@example.com',
         'betatester14@example.com',
         'betatester15@example.com',
         'betatester16@example.com',
         'betatester17@example.com',
         'betatester18@example.com' 
        ]

功能如下:

async (req, res, done) => {
    if (!req.body) {
      return res.status(404).json({ message: "Missing query parameters" });
      done();
    }

    try {
      const selectedTemplate = await db.oneOrNone("SELECT * FROM templates WHERE userid=$1 and uniqueTemplateName=$2", [req.session.id, uniquetemplatename]);
      if (!selectedTemplate) {
        return res.status(404).json({ message: "Unable to locate selected template" });
        done();
      }
      console.log('selectedTemplate', selectedTemplate);

      let subscriberEmails = [];
      await each(selectedTemplate.plans, async plan => {
        const emails = await db.any("SELECT email FROM subscribers WHERE userid=$1 AND planName=$2", [req.session.id, plan])
        each(emails, ({email}) => subscriberEmails.push(email))
        console.log('Found emails: ', subscriberEmails);
      })

      console.log('Selected emails: ', subscriberEmails); 
      res.status(500).json({ message: "Route not configured yet" })
    } catch (err) { res.status(500).json({ message: err }); done(); }
  }

大大简化的数据库结构:

├── Template
│   └── Plans (references an array of unique plan name(s))
|
|── Plan
|   └── PlanName (unique plan name)
|
│── Subscriber
|   └── PlanName (references a single unique plan name)
|   └── Email (unique email)

我尝试使用db.task(),但同样,在Express发送回邮件之前,查询没有解决。

1 个答案:

答案 0 :(得分:1)

找出问题所在。以防万一其他人迷失了这种困境:“ map”和“ each”之类的功能无法处理异步/等待。相反,他们只是返回一个未决的Promise。因此,您需要使用Bluebird之类的库,该库实现基于Promise的each / map / etc函数(在“集合”下)。

上述解决方法可以起作用:

try {
  await db.task('create-message', async t => {
    const selectedTemplate = await t.oneOrNone(findTemplateByName, [req.session.id, uniquetemplatename])
    if (!selectedTemplate) return sendError(unableToLocate('template'), res, done);
    const { fromsender, subject, message, plans, templatename } = selectedTemplate;

    let subscriberEmails = [];
    await Promise.each(plans, async plan => {
        const emails = await t.any(getAllEmailsByPlan, [req.session.id, plan]);
        each(emails, ({email}) => subscriberEmails.push(email));
    })

    if (isEmpty(subscriberEmails)) return sendError(unableToLocate('subscribers in the selected plan(s)'), res, done);

    const msg = {
        to: subscriberEmails,
        from: fromsender,
        replyTo: fromsender,
        subject: subject,
        html: message
    };

    await mailer.sendMultiple(msg);

    await t.none(createMessageTransaction, [req.session.id, templatename, fromsender, subject, currentDate, plans]);

    await t.none(createNotification, [req.session.id, 'mail_outline', `The following template: ${templatename} has been sent out to the subscibers in the following ${plans.length > 1 ? "plans" : "plan"}: ${plans}.`, date]);

    return res.status(201).send(null);
  })
} catch (err) { return sendError(err, res, done); }