0

I'm working on some labmda code in Node.js, and I want to pass an item gotten from DynamoDB with getitem to some code. Here's what I have:

const Alexa = require('ask-sdk'); 
const AWS = require ('aws-sdk');
AWS.config.update({region: 'us-east-1'});
//replace dynamo later with dynamo
dynamodb = new AWS.DynamoDB();
//const appId = 'REPLACE WITH YOUR SKILL APPLICATION ID';

const date = new Date(Date.now()).toString();
const date2 = date.substring(0,16);
const time = date.substring(16,24);

const LaunchRequestHandler = {
    canHandle(handlerInput) {
        //first we assign the requestEnvelope request to the request variable
        const request = handlerInput.requestEnvelope.request;
        //conditions to determine the requests this handler can handle
        //now using the request variable, we return true if it equals the one we want
        //in this case LaunchRequest
        return request.type === 'LaunchRequest'
    },
    handle(handlerInput) {
        //execution logic for the handler
        // ie What exactly do we do
        const speechOutput = 
            "Welcome to Track it, you can tell me who you lent things to, \
            or where you put an item. For example I lent the saw to Mike, or I put the saw in the workshop."
        return handlerInput.responseBuilder
            .speak(speechOutput)
            .getResponse();
    }
}


const GaveIntentHandler = {
    canHandle(handlerInput) {
      return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && handlerInput.requestEnvelope.request.intent.name === 'GaveIntent';
    },
    handle(handlerInput,event) {
        // setting variable attributes to handle things like counters
        const attributes = handlerInput.attributesManager.getSessionAttributes();
        // personName and itemName are pulling the slots information from the intent
        const personName = handlerInput.requestEnvelope.request.intent.slots.lenderPerson.value;
        const itemName = handlerInput.requestEnvelope.request.intent.slots.storedObject.value;
        const currentUser = handlerInput.requestEnvelope.session.user.userId;

       //begin DB code
       var params = {
        TableName: 'TrackItDB',
        Item: {
          'userID' : {S: currentUser},
          'storedObject' : {S: itemName},
          'lenderPerson' : {S: personName},
          'objectStatus' : {S: 'lent'},
          'transactionDate': {S: date},
        },
        ConditionExpression: 'attribute_not_exists(storedObject)'
      };
      console.log(params);

// putItem in database only if it doesn't already exist
    dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log("Error", err);
            console.log("That item already exists");
                } else {
            console.log("Success", data);
                }
               });

        console.log(personName);
        console.log(itemName);
        console.log(currentUser);

        const speechOutput = 'You Gave ' + personName + ' the ' + itemName;

      return handlerInput.responseBuilder
        .speak(speechOutput)
        .withSimpleCard('Track It', speechOutput)
        .getResponse();
    }
  };

const PutIntentHandler = {
    canHandle(handlerInput) {
      return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && handlerInput.requestEnvelope.request.intent.name === 'PutIntent';
    },
    handle(handlerInput) {
        const itemName = handlerInput.requestEnvelope.request.intent.slots.storedObject.value;
        const LocationName = handlerInput.requestEnvelope.request.intent.slots.storageLocation.value;
        const currentUser = handlerInput.requestEnvelope.session.user.userId;


       //begin DB code
       var params = {
        TableName: 'TrackItDB',
        Item: {
          'userID' : {S: currentUser},
          'storedObject' : {S: itemName},
          'lenderPerson' : {S: LocationName},
          'objectStatus' : {S: 'stored'},
          'transactionDate': {S: date},
        },
        ConditionExpression: 'attribute_not_exists(storedObject)'
      };

      dynamodb.putItem(params, function(err, data) {
        if (err) {
            console.log("Error", err);
            console.log("That item already exists");
        }
        else {
            console.log("Success", data);
        }
    });
       //end DB code
       const speechOutput = 'You put the ' + itemName + ' in the ' + LocationName;

      return handlerInput.responseBuilder
        .speak(speechOutput)
        .withSimpleCard('Hello World', speechOutput)
        .getResponse();
    }
  };

const WhereIsIntentHandler = {
    canHandle(handlerInput) {
      return handlerInput.requestEnvelope.request.type === 'IntentRequest'
        && handlerInput.requestEnvelope.request.intent.name === 'WhereIsIntent';
    },
    handle(handlerInput) {
        const itemName = handlerInput.requestEnvelope.request.intent.slots.storedObject.value;
        const currentUser = handlerInput.requestEnvelope.session.user.userId;
// begin DB query
      var params = {
        Key: {
         "userID": {
           S: currentUser
          }, 
         "storedObject": {
           S: itemName
          }
        }, 
        TableName: "TrackItDB"
       };
// End DB Query


       dynamodb.getItem(params, function(err, data) {
        if (err) {
          console.log("Error", err); 
              }// an error occurred
        else  {   
        console.log("Success", data);           // successful response
        const LocationName = data.Item.lenderPerson.S; 
        const speechOutput = 'Your ' + itemName + ' is in the ' + LocationName;

         return handlerInput.responseBuilder
            .speak(speechOutput)
            .withSimpleCard('Hello World', speechOutput)
            .getResponse();    
              }
        }); 

    }
  };

const HelpIntentHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest'
         && handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
    const speechOutput = 'Welcome to Track it, you can tell me who you lent things to, or where you put an item. For example I lent the saw to Mike, or I put the saw in the workshop.';

    return handlerInput.responseBuilder
        .speak(speechOutput)
        .reprompt(speechOutput)
        .withSimpleCard('Hello World', speechOutput)
        .getResponse();
    }
};

const CancelAndStopIntentHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'IntentRequest'
         && (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent'
           || handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent');

    },
    handle(handlerInput) {
        const speechOutput = 'Goodbye!';

        return handlerInput.responseBuilder
            .speak(speechOutput)
            .withSimpleCard('Hello World', speechOutput)
            .getResponse();
    }
};

const SessionEndedRequestHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'SessionEndedRequest';
    },
    handle(handlerInput) {
        //any cleanup logic goes here
        return handlerInput.responseBuilder.getResponse();
    }
};


const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
    .addRequestHandlers(
        LaunchRequestHandler,
        GaveIntentHandler,
        PutIntentHandler,
        WhereIsIntentHandler,
        HelpIntentHandler,
        SessionEndedRequestHandler,
        CancelAndStopIntentHandler
    )
    .lambda()

I'm trying to pass the "itemName and LocationName to the const speechOutput variable so I can have Alexa speak it for me.

It will work in the console log, but not later outside the getitem function. FYI, I know I shouldn't have the const speechOutput twice, and it isn't like that in my code; I just put it there to show what I'm trying to do.

1 Answer 1

1

You need to move the responseBuilder code snippet within the getItem function' else part. Do not declare the const speechOutput twice.

handle(handlerInput) {
    const itemName =
        handlerInput.requestEnvelope.request.intent.slots.storedObject.value;
    const currentUser =
        handlerInput.requestEnvelope.session.user.userId;

    // Begin database query
    var params = {
        Key: {
            "userID": {
                S: currentUser
            },
            "storedObject": {
                S: itemName
            }
        },
        TableName: "TrackItDB"
    };
    // End DB Query

    //const speechOutput = 'test'
    dynamodb.getItem(params, function(err, data) {
    if (err) {
        console.log("Error", err);
    } // An error occurred
    else {
        console.log("Success", data); // Successful
                                      // response
        const LocationName = data.Item.lenderPerson.S;
        const speechOutput = 'Your ' + itemName + ' is in the ' +
                             LocationName;
        // Speak the output
        return handlerInput.responseBuilder
            .speak(speechOutput)
            .withSimpleCard('Hello, World!', speechOutput)
            .getResponse();
        console.log(speechOutput);
    }
});
//const speechOutput = 'Your ' + itemName + ' is in the ' +
                     LocationName;
}
Sign up to request clarification or add additional context in comments.

4 Comments

The indentation is a mess. I am not sure if you have changed anything, but you may be able to use content from the fixed question.
Thanks, @PeterMortensen for pointing that out. I have updated the answer accordingly.
OK So I've tried this, and While I no longer get any error, I also don't get any speech output.
Hi Guys, I've edited the original question and added the complete code in hopes someone can help me. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.