Skip to content

Instantly share code, notes, and snippets.

@ankkal
Created May 2, 2018 17:14
Show Gist options
  • Save ankkal/3bfe1ad6d6e6358058f1d21c5c5c4e8a to your computer and use it in GitHub Desktop.
Save ankkal/3bfe1ad6d6e6358058f1d21c5c5c4e8a to your computer and use it in GitHub Desktop.
Request and Response Interceptors for Persistance in Node JS V2 SDK
const RequestPersistenceInterceptor = {
process(handlerInput) {
if(handlerInput.requestEnvelope.session['new']) {
return new Promise((resolve, reject) => {
handlerInput.attributesManager.getPersistentAttributes()
.then((sessionAttributes) => {
sessionAttributes = sessionAttributes || {};
sessionAttributes['launchCount'] += 1;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
handlerInput.attributesManager.savePersistentAttributes()
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
});
} // end session['new']
}
};
const ResponsePersistenceInterceptor = {
process(handlerInput, responseOutput) {
const ses = (typeof responseOutput.shouldEndSession == "undefined" ? true : responseOutput.shouldEndSession);
if(ses || handlerInput.requestEnvelope.request.type == 'SessionEndedRequest') { // skill was stopped or timed out
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes['lastUseTimestamp'] = new Date(handlerInput.requestEnvelope.request.timestamp).getTime();
handlerInput.attributesManager.setPersistentAttributes(sessionAttributes);
return new Promise((resolve, reject) => {
handlerInput.attributesManager.savePersistentAttributes()
.then(() => {
resolve();
})
.catch((err) => {
reject(err);
});
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment