Firebase函数保证无法正确触发

时间:2019-01-20 03:08:28

标签: node.js firebase google-cloud-functions

我很难理解Firebase函数中的诺言。我有一个功能,可以侦听存储桶中的新文件,然后向用户发送电子邮件以及向他们发送Discord消息。我得到的结果不一致,而且我很确定这与答应和回调设置不正确有关。

exports.sendSetup = functions.storage.bucket('*the-bucket-id*').object().onFinalize((object) => {
      // Get a URL for the new config file
      console.log('New conf file: ' + object.name);
      const { Storage } = require('@google-cloud/storage');

  const storage = new Storage({
    projectId: '*the-project-id*',
    keyFilename: 'googleServiceAccountKey.json'
  });
  var bucket = storage.bucket('*the-bucket-name*');

  const file = bucket.file(object.name);
  console.log('Generating download url for file ' + object.name);
  return file.getSignedUrl({
    promptSaveAs: '*the-file-name*',
    action: 'read',
    expires: '03-09-2491'
  }).then(signedUrls => {
    var split = object.name.split("/");
    var env = split[0];
    var customer_id = split[1];
    getCustomerDetails(customer_id, signedUrls[0], env);
  });
});

function getCustomerDetails(customer_id, fileUrl, env) {
  console.log('Retrieving customer details for customer id ' + customer_id + ' from Stripe');
  var stripe = stripeLive;
  if (env == 'test') {
    stripe = stripeTest;
  }

  stripe.customers.retrieve(
    customer_id,
    function (err, customer) {
      if (err == null) {
        sendMail(fileUrl, customer.email, customer_id, customer.metadata.name);
        console.log('discordId= ' + customer.metadata.discordId);
        if (customer.metadata.discordId != 'undefined') {
          sendDiscord(fileUrl, customer.metadata.discordId, customer.metadata.discordName);
        }
        console.log('Finished');
      } else {
        console.log(err);
      }
    }
  );
}

function sendDiscord(fileUrl, discordId, discordName) {
  console.log('Attempting to send a discord message to Discord id ' + discordId);
  const Discord = require('discord.js');
  const client = new Discord.Client();
  client.login('*discord-api-key*');
  client.once('ready', () => {
    console.log('Discord client ready');
    client.fetchUser(discordId)
      .then((User) => {
        console.log('Got Discord user object. Attempting to send message');
        return User.send({
          embed: {
            color: 3447003,
            fields: [
              {
                name: 'Hey ' + discordName + '!',
                value: 'Below are the instructions to get you up and running'
              },
              {
                name: '**Step 1**',
                value: 'some instructions'
              }
            ]
          }
        });
      })
      .catch((err) => {
        console.log(err);
      })
  });
}

function sendMail(fileUrl, customer_email, customer_id, customer_name) {
  console.log('customer_name in sendMail function = ' + customer_name);
  var firstName = customer_name.substring(0, customer_name.indexOf(' '));
  console.log(firstName);

  const sgMail = require('@sendgrid/mail');
  sgMail.setApiKey(*sendGridApiKey*);
  sgMail.setSubstitutionWrappers('{{', '}}'); // Configure the substitution tag wrappers globally

  const msg = {
    to: customer_email,
    subject: 'Welcome!',
    from: {
      email: 'noreply@example.com.au',
      name: 'me'
    },
    text: 'Let\'s get you setup...',
    html: '<p></p>',
    templateId: '*template-id*',
    substitutions: {
      first_name: firstName,
      file_url: fileUrl
    },
  };
  console.log('Sending email to ' + customer_email + ' customer id:' + customer_id);
  sgMail.send(msg);
}

我已经阅读了很多有关Promise和回调的文章,但是似乎无法绕开它。 “ sendSetup”函数实际上返回OK,但似乎在getCustomerDetails函数开始时就停止了。感谢任何协助!我有点迷路了!

0 个答案:

没有答案