Search code examples
node.jsmodulealexa-skills-kitvoice

How to bring the Alexa request handler in another module


i am looking for an option how to bring my Alexa request handler in another module. This is my approach:

  //index.js
  var Alexa = require('ask-sdk-core');
  var tests = require('./secondModule');

  var LaunchRequestHandler = tests('LaunchRequest','Hello, is this working?')

  var skillBuilder = Alexa.SkillBuilders.custom();

  exports.handler = skillBuilder
    .addRequestHandlers(
      LaunchRequestHandler
      )      
    .lambda();

and my second module looks like this:

//secondModule.js
var Alexa = require('ask-sdk-core');

function Test(requestName, speechText){

    var request = requestName+"Handler"
    console.log("log: " +request)

    request = {
        canHandle(handlerInput) {
            console.log("log: "+request)
            return handlerInput.requestEnvelope.request.type === requestName;
        },
        handle(handlerInput) {

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

}

module.exports = Test

But if i try it like this, the error '"errorMessage": "Cannot read property 'canHandle' of undefined"' comes up. Do you maybe have an idea how i could do it? I am pretty new with Node and JavaScript

here is my package.json:

  {
  "name": "hello",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "actions-on-google": "^2.5.0",
    "ask-sdk-core": "^2.0.0",
    "ask-sdk-model": "^1.0.0"
  }
}

Solution

  • You're not returning the request. Change your Test function to this:

    function Test(requestName, speechText){
    
      var request = requestName+"Handler"
      console.log("log: " +request)
    
      return request = {
        canHandle(handlerInput) {
          console.log("log: "+request)
          return handlerInput.requestEnvelope.request.type === requestName;
        },
        handle(handlerInput) {
    
          return handlerInput.responseBuilder
                .speak(speechText)
                .reprompt(speechText)
                .withSimpleCard('Hello World', speechText)
                .getResponse();
        },
      };
    }
    

    This should work now!