在Module - node.js中将对象导出为数组

时间:2018-06-18 11:10:49

标签: javascript node.js module export

请参阅我的附件。如何以一种方式从文件handlers.js导出对象,我可以写入index.js:

 alexa.SkillBuilders.custom()
 .addRequestHandlers(handlers)

我猜它必须是一个对象数组,或类似的东西。双重打字所有处理程序,都没有乐趣。非常感谢你。

档案:index.js

const express = require('express');
const bodyParser = require('body-parser');
const alexa = require('ask-sdk-core');
const verifier = require('alexa-verifier-middleware');

const handlers = require('./handlers');

const port = 3000;
const path = '/laborsteuerung';
const app = express();

app.get('/', (req, res) => {
    res.send('Online');
});

app.post(path, verifier, bodyParser.json(), function (req, res) {

    alexa.SkillBuilders.custom()
    .addRequestHandlers(handlers.LaunchRequestHandler,
                        handlers.DriveRobotIntent)
    .create()
    .invoke(req.body)
    .then(function(responseBody) {
        res.json(responseBody);
    })
    .catch(function(error) {
        console.log(error);
        res.status(500).send('Error during the request');
    });

})

app.listen(port, () => {
    console.log('Server listening on port ' + port + '!');
});

文件:handlers.js

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return handlerInput.requestEnvelope.request.type === 'LaunchRequest';
  },
  handle(handlerInput) {
    return handlerInput.responseBuilder
      .speak('Laborsteuerung gestartet - Befehl bitte')
      .reprompt('Befehl bitte')
      .getResponse();
  },
};

const DriveRobotIntent = {
  canHandle(handlerInput) {
    const request = handlerInput.requestEnvelope.request;

    return request.type === 'IntentRequest' 
      && request.intent.name === 'DriveRobotIntent';
  },
  handle(handlerInput) {
    let prompt = handlerInput.requestEnvelope.request.intent.slots.robot_name.value + ' ' +
             handlerInput.requestEnvelope.request.intent.slots.direction.value;
    console.log(prompt);
    return handlerInput.responseBuilder
      .speak(prompt)
      .getResponse();
  },
};

module.exports = {  LaunchRequestHandler,
                    DriveRobotIntent };

1 个答案:

答案 0 :(得分:0)

module.exports = {  handler: [LaunchRequestHandler,DriveRobotIntent]};
在index.js代码中,您可以使用spread运算符来分配参数

alexa.SkillBuilders.custom()
.addRequestHandlers(...handlers.handler)