使用导出处理程序firebase变量值"联系" aws lambda函数中的全局(外部导出处理程序)

时间:2017-02-18 14:16:09

标签: javascript amazon-web-services firebase aws-lambda alexa-skills-kit

我在aws中使用firebase并希望变量' contact'在一个其他函数中使用的exports处理程序中,为了让它成为全局函数,它遵循异步调用,这就是为什么无法将它作为全局变量返回的想法,这是我的代码:

'use strict';
var firebase = require('firebase');

/**
 * This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
 * The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well as
 * testing instructions are located at http://amzn.to/1LzFrj6
 *
 * For additional samples, visit the Alexa Skills Kit Getting Started guide at
 * http://amzn.to/1LGWsLG
 */


// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: 'PlainText',
            text: output,
        },
        card: {
            type: 'Simple',
            title: `SessionSpeechlet - ${title}`,
            content: `SessionSpeechlet - ${output}`,
        },
        reprompt: {
            outputSpeech: {
                type: 'PlainText',
                text: repromptText,
            },
        },
        shouldEndSession,
    };
}

function buildResponse(sessionAttributes, speechletResponse) {
    return {
        version: '1.0',
        sessionAttributes,
        response: speechletResponse,
    };
}


// --------------- Functions that control the skill's behavior -----------------------

function getWelcomeResponse(callback) {
    // If we wanted to initialize the session to have some attributes we could add those here.

    const sessionAttributes = {};
    const cardTitle = 'Welcome';
    const speechOutput = 'Welcome to the Alexa Skills Kit sample. ' +
        'Please ask me amy contact by saying, amy contact is 7389220636';
    // If the user either does not reply to the welcome message or says something that is not
    // understood, they will be prompted again with this text.
    const repromptText = 'Please ask me amy contact by saying, ' +
        'amy contact is 7389220636';
    const shouldEndSession = false;

    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

function handleSessionEndRequest(callback) {
    const cardTitle = 'Session Ended';
    const speechOutput = 'Thank you for trying the Alexa Skills Kit sample. Have a nice day!';
    // Setting this to true ends the session and exits the skill.
    const shouldEndSession = true;

    callback({}, buildSpeechletResponse(cardTitle, speechOutput, null, shouldEndSession));
}

function createContactAttributes(contactInfo) {
    return {
        contactInfo,
    };
}

/**
 * Sets the contact in the session and prepares the speech to reply to the user.
 */
function setContactInSession(intent, session, callback) {
    const cardTitle = intent.name;
    const contactInfoSlot = intent.slots.Contact;
    let repromptText = '';
    let sessionAttributes = {};
    const shouldEndSession = false;
    let speechOutput = '';

    if (contactInfoSlot) {
        const contactInfo = contactInfoSlot.value;
        sessionAttributes = createContactAttributes(contactInfo);
        speechOutput = `I now know amy contact is ${contactInfo}. You can ask me ` +
            "amy contact by saying, what's amy contact?";
        repromptText = "You can ask me amy  by saying, what's amy contact?";
    } else {
        speechOutput = "I'm not sure what's amy contact. Please try again.";
        repromptText = "I'm not sure what's amy contact.";
    }

    callback(sessionAttributes,
        buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}

function getContactFromSession(intent, session, callback) {
    let contactInfo;
    const repromptText = null;
    const sessionAttributes = {};
    let shouldEndSession = false;
    let speechOutput = '';

    if (session.attributes) {
        contactInfo = session.attributes.contactInfo;
    }

    if (contactInfo) {
        speechOutput = `Amy's contact is ${contactInfo}. Goodbye.`;
        shouldEndSession = true;
    } else {
        speechOutput = "I'm not sure what's amy contact is, you can say, amy contact " +
            ' is 7389220636';
    }

    // Setting repromptText to null signifies that we do not want to reprompt the user.
    // If the user does not respond or says something that is not understood, the session
    // will end.
    callback(sessionAttributes,
        buildSpeechletResponse(intent.name, speechOutput, repromptText, shouldEndSession));
}


// --------------- Events -----------------------

/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    console.log(`onSessionStarted requestId=${sessionStartedRequest.requestId}, sessionId=${session.sessionId}`);
}

/**
 * Called when the user launches the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log(`onLaunch requestId=${launchRequest.requestId}, sessionId=${session.sessionId}`);

    // Dispatch to your skill's launch.
    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log(`onIntent requestId=${intentRequest.requestId}, sessionId=${session.sessionId}`);

    const intent = intentRequest.intent;
    const intentName = intentRequest.intent.name;

    // Dispatch to your skill's intent handlers
    if (intentName === 'MyContactIsIntent') {
        setContactInSession(intent, session, callback);
    } else if (intentName === 'WhatsMyContactIntent') {
        getContactFromSession(intent, session, callback);
    } else if (intentName === 'AMAZON.HelpIntent') {
        getWelcomeResponse(callback);
    } else if (intentName === 'AMAZON.StopIntent' || intentName === 'AMAZON.CancelIntent') {
        handleSessionEndRequest(callback);
    } else {
        throw new Error('Invalid intent');
    }
}

/**
 * Called when the user ends the session.
 * Is not called when the skill returns shouldEndSession=true.
 */
function onSessionEnded(sessionEndedRequest, session) {
    console.log(`onSessionEnded requestId=${sessionEndedRequest.requestId}, sessionId=${session.sessionId}`);
    // Add cleanup logic here
}


// --------------- Main handler -----------------------

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function(event, context, callback) {
    try {
        console.log(`event.session.application.applicationId=${event.session.application.applicationId}`);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */
        /*
        if (event.session.application.applicationId !== 'amzn1.echo-sdk-ams.app.[unique-value-here]') {
             callback('Invalid Application ID');
        }
        */

        if (event.session.new) {
            onSessionStarted({
                requestId: event.request.requestId
            }, event.session);
        }

        if (event.request.type === 'LaunchRequest') {
            onLaunch(event.request,
                event.session,
                (sessionAttributes, speechletResponse) => {
                    callback(null, buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === 'IntentRequest') {
            onIntent(event.request,
                event.session,
                (sessionAttributes, speechletResponse) => {
                    callback(null, buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === 'SessionEndedRequest') {
            onSessionEnded(event.request, event.session);
            callback();
        }
        if (firebase.apps.length == 0) {
            firebase.initializeApp({
                serviceAccount: "",
                databaseURL: ""
            });
        }
        var ref = firebase.database().ref();
        var usersRef = ref.child('users');


        usersRef.once('value').then(function(snap) {
            //console.log(snap.child("messages").key, "\n\n");
            //console.log(snap.ref.toString(), "\n\n");
            snap.forEach(function(childSnapshot) {
                var childKey = childSnapshot.val();
                var contact = childKey.Contact;
                console.log('Firebase data: ', contact);
                firebase.database().goOffline();
                callback(contact);

            });

        });

    } catch (err) {
        callback(err);
    }
};

0 个答案:

没有答案