0

Is there a neat way to organize Node.js Alexa code. As my intents in the interaction model increases, the lines of code in the index.js of the lambda increased to a point where it is unmanageable. Is there an example of how to structure Alexa Node.js code.

Ajay
  • 43
  • 4

1 Answers1

0

I usually put all of my state handlers into their own files and then export them. I also put commonly used data/config in to a 'resources file' and export that.

resources.js

const ACCESS_TOKEN = 'sometoken';
const GAME_STATES = {
    TRIVIA: "_TRIVIAMODE", // Asking trivia questions.
    START: "_STARTMODE", // Entry point, start the game.
    HELP: "_HELPMODE", // The user is asking for help.
   };
const APP_ID = 'appid';
const HOST = 'http://localhost:8000';
const API_ROUTES = {
    QUIZZES: HOST + '/api/quizzes/', //all quizzes
    CATEGORIES: HOST + '/api/categories/' //all categories
};
const API_OPTIONS = {
    url: '',
    headers: {
        'Accept': 'application/json',
        "Authorization" : "Bearer " + ACCESS_TOKEN
    }
};

module.exports = {
    ACCESS_TOKEN: ACCESS_TOKEN,
    GAME_STATES: GAME_STATES,
    APP_ID: APP_ID,
    API_OPTIONS: API_OPTIONS,
    API_ROUTES: API_ROUTES
};

My index.js just requires these files and is the simple entry point to the app.

index.js

'use strict';

const Alexa = require('alexa-sdk');
const helpers = require('./helpers');
const resources = require('./resources');
const newsessionhandlers = require('./newsessionhandlers');
const helpstatehandlers = require('./helpstatehandlers');
const triviastatehandlers = require('./triviastatehandlers');
const startstatehandlers = require('./startstatehandlers');

const APP_ID = resources.APP_ID;

exports.handler = function (event, context) {
    const alexa = Alexa.handler(event, context);
    alexa.appId = APP_ID;
    alexa.resources = resources.languageString;
    alexa.registerHandlers(newsessionhandlers.newSessionHandlers, startstatehandlers.startStateHandlers, triviastatehandlers.triviaStateHandlers, helpstatehandlers.helpStateHandlers);
    alexa.execute();
};
WJDev
  • 191
  • 1
  • 10
  • What If I have a separate folder for handlers. If I am having a separate folder I have to place a copy of node_modules in that directory as well. How do I make it point to the node_modules in the root directory – Ajay Feb 27 '18 at 16:05