I'm trying to write a quiz game where Alexa asks 10 random questions from a list, and keeps track of the score, then announces it. I'm using a Node.js Lambda function to do so.
I wrote a class, QuizMaster
, which runs the quiz: it asks the user their preferred categories and difficulty level, creates the randomized list of question with randomized A/B/C answer slots, and checks whether a supplied answer is correct for the last-spoken question.
Here's where things get tricky for me: where can I save the reference to that QuizMaster
instance? If I create it as a variable outside the intent handlers, it works fine for the first time, but then the quizmaster is still around if the user re-invokes the skill, and will immediately re-announce their final score and end the game. This confuses me a bit, because my mental model was that every time a Lambda endpoint is hit it's like Amazon is running node index.js
and when the session ends, execution ends. But I suppose I'm wrong -- is it more like Amazon runs node index.js
once, keeping it open in a loop listening for events, and every event goes to the handler function? So if I run it twice in a row, I've still got those old variables around with their old values? Does that mean if 10 users run my Alexa skill simultaneously, they all share the same values for those variables/modify each other's state? Or would it be like AWS running the file 10 times and charging me for 10x the memory of a single execution?
So, I guess I'm meant to store state in a database or directly attached to the session (in the Alexa Node SDK, this.attributes
). So do I need to rewrite my application in such a way that I can serialize the state, attach it to the session, then pull the state out -- I can't keep a QuizMaster
instance around to keep track of things per-user-session?