Microsoft bot framework save separately conversations or sessions - node.js

I got a Microsoft bot framework chatbot deployed on Azure and I´m using Tedious to save my conversations, thing is, bot it's being used on a web and many persons can open it to interact simultaneosly, but when I save a conversation from an user, it saves all the other interactions that have been made by other users at the same time, I need that each user has it's own conversation saved separately even if they are interacting with the chatbot at the same time...
Here's my code, maybe I'm missing something:
Bot.js
//SQL Connection
var Connection = require('tedious').Connection;
var config = {
server: 'myserver',
authentication: {
type: 'default',
options: {
userName: 'myuser',
password: 'mypass'
}
},
options: {
encrypt: true,
database: 'mydatabase'
}
};
const connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
});
var Request = require('tedious').Request
var TYPES = require('tedious').TYPES;
// Function to save the conversation and bot ids
function executeConversationStatement(bot, cid, ulg ) {
request = new Request("INSERT INTO table (bot_id, conversationID, conversation_date, userlogged) VALUES (#bot, #cid, CURRENT_TIMESTAMP, #ulg); SELECT ##IDENTITY AS ID",function(err) {
if (err) {
console.log(err);}
});
request.addParameter('bot', TYPES.Int, bot);
request.addParameter('cid', TYPES.NVarChar, cid);
request.addParameter('ulg', TYPES.NVarChar, ulg);
request.on('row', function(columns) {
insertedcid = columns[0].value; // This is the id I pass later
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
console.log("Conversation id of inserted item is " + column.value);
}
});
});
connection.execSql(request);
}
// Here on members added I save the conversation id generated by the framework
class BOT extends ActivityHandler {
constructor(conversationState,userState,telemetryClient) {
super();
this.conversationState = conversationState;
this.userState = userState;
this.dialogState = conversationState.createProperty("dialogState");
this.previousIntent = this.conversationState.createProperty("previousIntent");
this.conversationData = this.conversationState.createProperty('conservationData');
const qnaMaker = new QnAMaker({
knowledgeBaseId: process.env.QnAKnowledgebaseId,
endpointKey: process.env.QnAEndpointKey,
host: process.env.QnAEndpointHostName
});
this.qnaMaker = qnaMaker;
this.onMessage(async (context, next) => {
await this.dispatchToIntentAsync(context);
await next();
});
this.onDialog(async (context, next) => {
await this.conversationState.saveChanges(context, false);
await this.userState.saveChanges(context, false);
await next();
});
this.onMembersAdded(async (context, next) => {
const { channelId, membersAdded } = context.activity;
actid = context._activity.id;
if (channelId === 'directline' || channelId === 'webchat') {
for (let member of membersAdded) {
if (member.id === context.activity.recipient.id) {
await context.sendActivity("Hi, I´m a chatbot to guide You");
try{
var saveqna = new executeConversationStatement(context._activity.id , 'Invitado');
}
catch{
console.log('Not saved');
}
}
}
}
await next();
});
}
//Finally, here I save the interaction:
async dispatchToIntentAsync(context) {
var result = await this.qnaMaker.getAnswers(context);
// Statement to save interaction with the insertedcid obtained above
var saveqnaint = new executeInteractionStatement(insertedcid, context._activity.text, result);
}
No matter if I use thet generated Id or the databse pk, I always keep the same identifier when multiple users are chatting, how can I got a separately Id for each session ?

Related

Send web push notifications to specific users conditionally

I am willing to use web-push notifications on my web app. I have already setup serviceWorkers on the front-end(React) and implemented web-push notifications on my backend(NodeJS). Now I just need to send notifications which are user specific, means only specific users should receive those notifications.
For e.g. In my web app's backend I will be receiving some live values. Say, there is a collection named
"users" where all the user's data will be stored. Now these users will have a field named "device" where the user will receive numeric values which will be updated within 40-50 seconds.
Now, their will be a threshold for these values. Say, for e.g. if the value reaches above 200 then that specific user should receive a push notification, letting them know that the device has reached it's limit.
How is it possible for me to create such user specific push notifications where the notification will be sent to only that user who's device value has reached above 200 ?. P.S I am using Mongoose for the database.
FrontEnd code(react.js)
sw.js:
self.addEventListener("notificationclick", function (event) {
// on Notification click
let notification = event.notification;
let action = event.action;
console.log("Notification====>", notification);
if (action === "confirm") {
console.log("Confirm clicked");
notification.close(); // Closes the notifcation
} else {
event.waitUntil(
clients.matchAll().then(function (clis) {
var client = clis.find(function (c) {
return c.visibilityState === "visible";
});
if (client !== undefined) {
// found open window
client.navigate("http://localhost:3000"); // means website opens on the same tab where user is on
client.focus();
} else {
// if client's window was not open
clients.openWindow("http://localhost:3000"); // when browser window is closed, open website
}
notification.close();
})
);
console.log(action); // name of action, basically id
}
});
self.addEventListener("notificationclose", function (event) {
console.log("Notification closed", event);
});
// triggers when we get an incoming push message
self.addEventListener("push", function (event) {
console.log("Push notifications recieved from eventListner", event);
var data = { title: "New!", content: "New things" };
if (event.data) {
// check if payload exists(from backend)
data = JSON.parse(event.data.text()); // recieve payload & store
}
var options = {
body: data.content,
icon: "https://iconarchive.com/download/i90141/icons8/windows-8/Cinema-Avengers.ico",
tag: "id1",
renotify: true,
};
event.waitUntil(self.registration.showNotification(data.title, options));
});
swReg.js:
if ("serviceWorker" in navigator) {
console.log("Registering service worker");
navigator.serviceWorker
.register("/sw.js")
.then(() => {
console.log("Service Worker has been registered");
})
.catch((err) => console.error(err));
}
function urlBase64ToUint8Array(base64String) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
function displayConfirmNotification() {
if ("serviceWorker" in navigator) {
const options = {
body: "After subscription managing done",
// icon: "/src/assets/img/pattern_react.png",
// tag:"" ==> in advanced options.
vibrate: [100, 50, 200],
// badge:""
tag: "confirm",
renotify: true,
actions: [
{ action: "confirm", title: "okay" }, // optnl icon:""
{ action: "cancel", title: "cancel" },
],
};
navigator.serviceWorker.ready.then(function (swreg) {
swreg.showNotification("Successfully subscribed sW", options);
});
}
}
function configPushSub() {
if (!("serviceWorker" in navigator)) {
return;
}
var reg;
navigator.serviceWorker.ready
.then(function (swreg) {
// access to sW registration
reg = swreg;
return swreg.pushManager.getSubscription(); // returns any existing subscription
})
.then(function (sub) {
// sub holds the current subscription, if subscription doesn't exist then it returns null
if (sub === null) {
// Create a new subscription
var vapidPublicKey = KEY;
var convertedPublicKey = urlBase64ToUint8Array(vapidPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly: true, // for security
applicationServerKey: convertedPublicKey, // for security & server storage
}); // create new subscription
} else {
// We already have a subscription
}
})
.then(function (newSub) {
// have to pass this subscription(new one) to backend
console.log("New subb =======>", newSub);
return fetch("http://localhost:8000/subscribeToPushNotifications", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
subscriptionObj: newSub,
}),
});
})
.then(function (res) {
if (res.ok) {
displayConfirmNotification();
}
})
.catch(function (e) {
console.log("err while subbing====>", e);
});
}
function askForNotificationPermission() {
Notification.requestPermission(function (result) {
console.log("User's choice", result);
if (result !== "granted") {
console.log("Permission rights not granted");
} else {
configPushSub();
// displayConfirmNotification();
}
});
}
if ("Notification" in window) {
askForNotificationPermission();
}
Backend:
API to subscribe:
exports.subscribeToPushNotifications = async (req, res) => {
const { subscriptionObj } = req.body;
// console.log("Subscription object=====>", subscriptionObj);
if (subscriptionObj != undefined || subscriptionObj != null) {
let newSubscription = new Subscription({
pushSubscription: subscriptionObj,
});
await newSubscription.save();
if (newSubscription) {
console.log(newSubscription);
return res.status(200).send("Subscription made");
} else {
console.log("Not subbed");
return res.status(400).send("Subscription not made");
}
} else {
console.log("Sub obj is null");
return res.status(400).send("Sub obj was null");
}
};
Checking if values are more than the threshold and then sending notification:(For example purposes). This is an example for single user only.
exports.checkStatus = async () => {
schedule.scheduleJob("*/10 * * * * *", async () => {
let subscriptions = await Subscription.find({});
let Email = "james#mail.com";
let findUser = await User.findOne({ Email });
if (findUser) {
if (findUser.device > 200) // findUser.device contains the value
{
for (let i = 0; i < subscriptions.length; i++) { //Notification will be sent to all users which I don't want.
webpush.sendNotification(
subscriptions[i].pushSubscription,
JSON.stringify({
title: "Alert",
content: "Value has reached it's limit",
})
);
}
}
}
});
};
How can I make this work such that only those users who's device's value has gone above 200 will only receive the notification and not all the subscribed users.

SQL select all statement in a node.js application returns a tedious deprecated error

So I went to the Microsoft documentation for node.js and trying to connect to a database and I went through step by step, installed tedious and when I try to run my code it's throwing an error saying:
tedious deprecated In the next major version of tedious, creating a new Connection instance will no longer establish a connection to the server automatically. Please use the new connect helper function or call the .connect method on the newly created Connection object to silence this message. internal\process\task_queues.js:79:11.
Does anyone know what this means?
CODE:
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'HIDDEN';
bot.on('ready', () => {
console.log('This bot is online!');
var Connection = require('tedious').Connection;
var config = {
server: '', //update me
authentication: {
type: 'default',
options: {
userName: '', //update me
password: '' //update me
}
},
options: {
// If you are on Microsoft Azure, you need encryption:
encrypt: true,
database: '' //update me
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
if(!err)
{
console.log("Connected");
executeStatement();
}
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
function executeStatement() {
request = new Request("SELECT * from tblCustomer;", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
})
bot.login(token);

Session expiring in Dialogflow

I came to know that context expires in 15 minutes but is there any way to solve it manually i.e by storing the previous conversation in dB so can we handle that session expiring issue or else the whole conversation(output context) under that session ID will get clear and need to start from the first.
exports.fulfillmenttext = functions.https.onRequest((req,res) =>{
const answer1 = req.body.Text;
console.log("Text said by the user",answer1);
const uid = answer1.substring(0,28);
console.log("uid1 is",uid);
const answer = answer1.substring(28);
console.log("answer is",answer);
const sessionId = uid;
var count,questvalue;
runSample();
async function runSample(projectId = 'xxxxxxx') {
const languageCode = 'en-US';
const credentials = {
client_email: 'xxxxxxxxxx',
private_key: 'xxxxxxxxx'
};
//Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient({
projectId,
credentials,
});
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
text: answer,
languageCode,
},
},
};
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
let action = result.action;
console.log("action is"+action);
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
const question = result.fulfillmentText;
console.log("question is",question);
const actionHandlers = {
'early': () => {
console.log('earlyaction1', action);
let name1 = JSON.stringify(result.parameters.fields.Name.stringValue);
name1 = name1.toString().replace(/"/g,"");
var data1 = {
Name: name1
};
var setDoc1 = admin.firestore().collection('User').doc(uid).collection("Popop").doc(uid).collection('Answers').doc('Earlyyears').update(data1);
},
'family': () => {
console.log('familyaction1', action);
let mname1 = JSON.stringify(result.parameters.fields.M_Name.stringValue);
let mname_string = mname1.toString().replace(/"/g,"");
var data20 = {
MName: mname_string
};
var setDoc20 = admin.firestore().collection('User').doc(uid).collection("Popop").doc(uid).collection('Answers').doc('Family').update(data20);
}
};
if (action === 'early') {
console.log('1');
actionHandlers[action]();
}
else if (action === 'family') {
console.log('2');
actionHandlers[action]();
}
res.status(200).send({"question":result.fulfillmentText,"action":action});
} else {
console.log(` No intent matched.`);
res.status(400).send({"action":"empty"});
}
}
});
I stumbled upon this problem as well. My solution was to save the userID and save the contexts to Firestore.
UPDATE:
This is how I stored Dialogflow's contexts in Firestore:
function saveContexts(userId, contexts) {
let UID = userId;
//get all contexts + parameters
if (contexts === undefined) {
console.log("contexts are undefined! returning");
return false;
}
db.collection("user-contexts-prod").doc(UID).set({
dateCreated: new Date(),
contexts: JSON.stringify(contexts)
})
.then(function () {
console.log("success!");
return true;
})
.catch(function (error) {
console.log("error writing document..", error);
return false;
});
}
Retrieving user contexts:
async function getContexts(userId) {
let UID = userId;
let docRef = db.collection("user-contexts-prod").doc(UID);
return docRef.get()
.then(res => {
if (res.exists) {
let contexts = JSON.parse(res.data().contexts);
console.log("<><> parsed contexts <><>: ");
console.log(contexts);
return contexts;
} else {
console.log(" UID DOES NOT EXIST!");
return false;
}
})
}
You can set the contexts again by looping over them and using the contextClient to create new contexts. Or use this method to loop through the contexts and find the one you need:
contexts.forEach(function(context) {
if (context.name === 'projects/{DIALOGFLOWPROJECTID}/agent/sessions/' + senderId + '/contexts/{CONTEXTNAME}') {
sessionData = context.parameters;
// all data that you saved in CONTEXTNAME is now available in the sessionData variable
}
});
Original answer:
Whenever a user started talking that didn't have any active contexts I check if I had the userID stored in my Database. If this user existed in my DB I retrieved the user information with all his data like this:
knownUser = await db.isKnownUser(senderId);
if (knownUser) {
//knownUser
console.log("Known user");
let userData = db.getUserDataById(senderId)
//initialize contexts with data you need
payload = returningUser_useSameData();
messenger.send(payload, senderId);
dashbot.logBotMessage(payload.toString, sessionId, intentName);
break;
} else {
//newUser
console.log("new user");
createContext('await_fillInTogether', '', sessionPath, sessionId, 1);
createContext('session', '', sessionPath, sessionId, 500);
payload = fillInTogetherNewUser();
messenger.send(payload, senderId);
dashbot.logBotMessage(payload.toString, sessionId, intentName);
break;
}

Handling result of Multiple async call and call the database after collecting result

Guys, I am new in node js and I am trying to do below steps
1) Calling the AWS API to create the Cognito user by passing data.
2)when all the request will be completed then i will insert all the record in the database.
3) user is the array of all the users.
Here is what I have done
const obj = new ReadCsvFile();
obj.readCSVFromAWS()
.then(result => {
const user = obj.getMigratedList();
for (const i in user) {
if (user[i] !== null && user[i] !== undefined) {
const uuid = obj.createUserInCognito(user[i]);
uuid.then(userAttribute => {
user[i].uuid = String(userAttribute.User.Attributes.values); //should complete all the request
});
}
}
})
.catch(err => {
console.log(err);
});
public async createUserInCognito(data: User) {
const CognitoIdentityServiceProvider = AWS.CognitoIdentityServiceProvider;
const client = new CognitoIdentityServiceProvider({ apiVersion: "2016-04-19" });
const params = {
UserPoolId: "us-east-2_lleSjp1bN" /* required */,
Username: data.email /* required */,
DesiredDeliveryMediums: ["EMAIL"],
ForceAliasCreation: false,
// email_verified: true,
// MessageAction: "SUPPRESS",
TemporaryPassword: data.password,
UserAttributes: [
{
Name: "email" /* required */,
Value: data.email
}
]
};
return await client.adminCreateUser(params).promise();
}
Problem
1) I want that all the request should complete of Cognito user.
2) Then I need to pass the list of users into the database.
3) I want to know how can i wait to complete all the request and then insert into the database.
Please help.
Use the code snippet written below :
const obj = new ReadCsvFile();
obj.readCSVFromAWS()
.then(result => {
const user = obj.getMigratedList();
for (const i in user) {
if (user[i] !== null && user[i] !== undefined) {
obj.createUserInCognito(user[i]).then(uuid=>{
uuid.then(userAttribute => {
user[i].uuid = String(userAttribute.User.Attributes.values); //should complete all the request
});
});
}
}
})
.catch(err => {
console.log(err);
});

SNS publish and Firebase Save Data does nothing in AWS Node.JS Lambda

I have been trying to use Cloud Messaging with my Lambda Function to send push notifications.
At first I tried to use SNS linked to Firebase. But calling SNS.publish does nothing... no errors, no timeouts just seems to ignore the call. Here is a snippet of where it goes wrong:
const intentName = event.request.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'Temperature') {
getPatientTemperature(intent, context,
function (internalcontext, speechOutput) {
//sns
//var outmessage = {Display: speechOutput};
var sns = new AWS.SNS({region:'us-east-1'});
//console.log(sns);
console.log('sending push');
sns.publish({
Message: speechOutput,
TopicArn: "arn:aws:sns:us-east-1:*************:MedicalAssistantDisplayUpdates",
Subject: "TestSNS"
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("SNS here 2");
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
console.log("SNS here 3");
});
context.succeed( buildResponse({}, buildSpeechletResponse("Sent",speechOutput, "no text", true)));
console.log("That's all folks");
});
} else {
throw new Error('Invalid intent');
}
It's full code:
/* eslint-disable func-names */
/* eslint-disable no-console */
//const Alexa = require('ask-sdk-core');
var mysql = require('mysql');
var AWS = require("aws-sdk");
var connection = mysql.createConnection({
host: "********************",
port: "****",
user: "*******",
password: "*****",
database: "**************"
});
//=========================================================================================================================================
//TODO: The items below this comment need your attention.
//=========================================================================================================================================
const SKILL_NAME = 'Medical Assistant';
const GET_TEMPERATURE_MESSAGE = '\'s temperature is ';
const HELP_MESSAGE = 'You can say tell me the latest tempearture of patient patient ID, or, you can say exit... What can I help you with?';
const HELP_REPROMPT = 'What can I help you with?';
const FALLBACK_MESSAGE = 'The Medical Assistant can\'t help you with that. It can help you retrieve a patient\'s tempearture. What can I help you with?';
const FALLBACK_REPROMPT = 'What can I help you with?';
const STOP_MESSAGE = 'Goodbye!';
// --------------- Helpers that build all of the responses -----------------------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: 'PlainText',
text: output,
},
card: {
type: 'Simple',
title: `${title}`,
content: `${output}`,
},
reprompt: {
outputSpeech: {
type: 'PlainText',
text: repromptText,
},
},
shouldEndSession,
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: '1.0',
sessionAttributes,
response: speechletResponse,
};
}
function getPatientTemperature(intent, context, callback) {
const cardTitle = intent.name;
const PatientID = intent.slots.PatientID.value;
console.log(PatientID);
let repromptText = '';
let sessionAttributes = {};
const shouldEndSession = false;
let speechOutput = '';
console.log('Then run MySQL code:');
//connection.connect(function(err) {
console.log('Inside connection.connect() callback');
//context.callbackWaitsForEmptyEventLoop = false;
//if (!err) {
console.log("Database is connected ... ");
connection.query("SELECT Temperature, Patient_Name FROM (SELECT * FROM (SELECT c.Temperature, p.Patient_Name, c.Recorded_Time FROM ConsultationRecords c, Patients p WHERE (c.Patient_ID = p.Patient_ID) AND c.Patient_ID = '"+ PatientID +"' AND c.Temperature IS NOT NULL)AS Alias ORDER BY Recorded_Time DESC LIMIT 1) AS RequiredTemp",
function(err, result) {
//connection.end();
console.log("Inside connection.query() callback")
if (!err) {
console.log("Query Successful! Ending Connection.");
//connection.end();
if (result.length > 0) {
if(result[0].Temperature == 'null'){
}
else{
speechOutput = result[0].Patient_Name+"'s temperature is "+result[0].Temperature;
console.log("Returning Response");
}
}
else{
speechOutput = "Patient ID not found in records";
console.log("Returning invalid ID Response");
}
callback(context, speechOutput);
} else {
console.log("Query error!");
}
});
// } else {
// console.log("Error connecting database ..." + err.message);
// connection.end();
// }
console.log("here end");
// });
}
function getWelcomeResponse(context) {
// 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 Medical Assistant. ' +
'You can ask for Patient information like Temperature';
// 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 = 'For example, say: what is the latest temparature of patient 1.';
const shouldEndSession = false;
console.log(`Send Welcome Response`);
context.succeed(buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
}
exports.handler = (event, context) => {
try {
if (event.session.new) {
// New Session
console.log("NEW SESSION");
}
// Fix for hardcoded context from simulator
//if(event.context && event.context.System.application.applicationId == 'applicationId'){
// event.context.System.application.applicationId = event.session.application.applicationId;
//}
switch (event.request.type) {
case "LaunchRequest":
console.log(`Launch Request`);
getWelcomeResponse(context);
console.log(`End Launch`);
break;
case "IntentRequest":
// Intent Request
console.log(`Intent Request`);
const intent = event.request.intent;
const intentName = event.request.intent.name;
// Dispatch to your skill's intent handlers
if (intentName === 'Temperature') {
getPatientTemperature(intent, context,
function (internalcontext, speechOutput) {
//sns
//var outmessage = {Display: speechOutput};
var sns = new AWS.SNS({region:'us-east-1'});
//console.log(sns);
console.log('sending push');
sns.publish({
Message: speechOutput,
TopicArn: "arn:aws:sns:us-east-1:**********:MedicalAssistantDisplayUpdates",
Subject: "TestSNS"
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("SNS here 2");
if (err) {
console.log(err.stack);
return;
}
console.log('push sent');
console.log(data);
console.log("SNS here 3");
});
context.succeed( buildResponse({}, buildSpeechletResponse("Sent",speechOutput, "no text", true)));
console.log("That's all folks");
});
} else {
throw new Error('Invalid intent');
}
break;
case "SessionEndedRequest":
// Session Ended Request
console.log(`SESSION ENDED REQUEST`);
break;
default:
context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);
}
} catch (error) {
context.fail(`Exceptiodn: ${error}`)
}
};
After console.log('sending push'); it correctly runs context.succeed and the final console.log.
For my second attempt I tried to use the Firebase Admin SDK to update the firebase database (figuring I can store my messages there and then trigger a push notification from firebase when an insertion is made). I created a whole new Lambda function to test that and again.. just seems to ignore usersRef.set call. Here is the full code for that function:
var admin = require("firebase-admin");
var serviceAccount = require("medicalassistantviewer-firebase-adminsdk-7xw02-266915e453.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://****************.firebaseio.com"
});
// As an admin, the app has access to read and write all data, regardless of Security Rules
var db = admin.database();
var ref = db.ref();
var usersRef = ref.child("Messages");
exports.handler = (event, context) => {
console.log("Let's start");
context.succeed(usersRef.set({
message2: {
Message: "testing again",
Token: "200"
},
message3: {
Message: "and again",
Token: "300"
}
}, function(err, data) {
//context.callbackWaitsForEmptyEventLoop = false;
console.log("messages not sent");
if (err) {
console.log(err.stack);
return;
}
console.log('messages sent');
console.log(data);
console.log("here");
}));
};

Resources