larry walker
larry walker

Reputation: 123

My function is no sending an email upon receiving params.finalemail

I created a function in IBM cloud functions to calculate nights between two dates and send an email. The nights calculation works perfectly.Watson sends the params.checkout and params.checkin and it returns the total nights.

When Watson sends the params.finalemail, the params is sent to the cloud function but no email is sent.

The way I have it setup in Watson is 2 nodes the first node sends the checkin/checkout, it works perfectly. The second node sends on the params.finalemail. But the email doesn't send.

/**
  *
  * main() will be invoked when you Run This Action.
  *
  * @param Cloud Functions actions accept a single parameter,
  *        which must be a JSON object.
  * 
  * @return which must be a JSON object.
  * 
*/
// using SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');

function sendmail(params) {


  /*    Replace YOUR-SENDGRID-API-KEY-GOES-HERE with
        the API Key you get from SendGrid.
  */
  sgMail.setApiKey('api')

  let msg = {}
  msg.to = '[email protected]'
  msg.from = '[email protected]'
  msg.subject = 'Your Reservation'
  msg.html = params.finalemail

  sgMail.send(msg,(error, json) => {
    if (error) {
      console.log(error)
    }
  })
  return { sent: 1 }
}

/**
  * For nights(), the params variable will look like:
  *     { "checkin": "YYYY-MM-DD", "checkout": "YYYY-MM-DD" }
  *     Example: { "checkin": "2019-12-01", "checkout": 2020-01-31" }
  *     date1 should always be the earliest date.
  * 
  * The date params are assumed to be valid dates. It is the
  * responsibility of the caller to pass in valid dates.
  * This routine does not error check the dates.
  * 
  * @return which must be a JSON object.
  *     It will be the output of this action.
  *     The number of nights between checkin and checkout.
  *     { nights: x }
  *
*/
function parseDate(str) {
  let ymd = str.split('-');
  return new Date(ymd[0], ymd[1]-1, ymd[2]);
}

function datediff(first, second) {
  // Take the difference between the dates and divide by milliseconds per day.
  // Round to nearest whole number to deal with DST.
  return Math.round((second-first)/(1000*60*60*24));
}

function nights(params) {
  let nights = 0;
  if (params.checkin && params.checkout) {
    nights = datediff(parseDate(params.checkin), parseDate(params.checkout))
    if (nights < 0) {
        nights = 0
    }
  }
  return { nights };
}

function main(params) {
  if (params['finalemail']) {
    return sendmail(params)
  }

  if (params['checkin'] && params['checkout']) {
    return nights(params)
  }

  return {}
}

exports.main = main

Upvotes: 0

Views: 62

Answers (0)

Related Questions