How to send arrays to email using angular and firestore - node.js

I'm trying to send array data from firestore database using sendgrid.
I have tried using the documentation to no luck.
export const newOrder = functions.firestore
.document("checkout/{checkoutId}/products/{productId}")
.onCreate(async (change, context) => {
// Read booking document
const postSnap = await db
.collection("checkout/{checkoutId}/products")
.doc(context.params.productId)
.get();
const booking = postSnap.data() || {};
//Email
const msg = {
to: "wilmutsami#gmail.com",
from: "test#example.com",
templateId: TEMPLATE_ID,
dynamic_template_data: {
subject: "Hey there, thank you for your order!",
name: [booking.name],
amount: [booking.amount]
}
};
//Send it
return sgMail.send(msg);
});

Related

flutter: subscribing user to different topics in one collection for push notifications fcm

i wanna subscribe my users to different "language" topics according to their preference so they receive notifications in the language they want
in my firestore i have a collection called notifications inside its document(default) i have two more collections .. english and arabic.
now in my shopping app i subbed the user to english topic to test if it works
_fcm.subscribeToTopic('english');
and here's my index.js code for cloud fuctions:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var newData;
exports.messageTrigger = functions.firestore.document('notifications/default/{languageId}/{messagesId}').onCreate(async (snapshot, context) => {
newData = snapshot.data();
const payload = {
notification: {
title: newData.message,
body: newData.body,
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
message: newData.message,
}
};
if (context.param.languageId === "english") {
await admin.messaging().sendToTopic('english', payload);
}
else if (context.param.languageId=== "arabic") {
await admin.messaging().sendToTopic('arabic', payload);
}
});
but when i create a document in the english collection inside notifications collection it doesnt work. anybody know why?
i fixed it by making my functions like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var newData;
exports.messageTrigger = functions.firestore.document('notifications/{notificationsId}').onCreate(async (snapshot, context) => {
newData = snapshot.data();
const payload = {
notification: {
title: newData.message,
body: newData.body,
},
data: {
click_action: 'FLUTTER_NOTIFICATION_CLICK',
message: newData.message,
}
};
if (newData.language === 'english'){
await admin.messaging().sendToTopic('english', payload);
}else if (newData.language === 'arabic'){
await admin.messaging().sendToTopic('arabic', payload);
}
});

I can't send emails - Firebase CloudFunctions

I'm new to Firebase Cloud Functions and I want to create a mailing system on it. I need to receive an email in my account (for example myemail#gmail.com) every time a new data is inserted in my Realtime Database.The email must contain the contents of the firebase node.
I tried to use this code, but when adding new data to the Realtime database, I don't get any emails:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'email#gmail.com',
pass: 'password'
},
});
admin.initializeApp();
exports.sendEmail = functions.database.ref('/reports/{postId}/{reportId}').onWrite(async (change) => {
const snapshot = change.after;
const val = snapshot.val();
const mailOptions = {
from: '"Report" <email#gmail.com>',
to: 'myemail#gmail.com',
};
// Building Email message.
mailOptions.subject = 'Report ' + val.tipo;
mailOptions.text = 'Content ' + val;
try {
await mailTransport.sendMail(mailOptions);
console.log('email sent! ');
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
Database:
"reports" : {
"-M2sV-8jze4u8di8rC6a" : {
"-M2smZT3YgGe6pbHb9ML" : {
"idAuthor" : "-M2sV-8jze4u8di8rC6a",
"idReport" : "-M2smZT3YgGe6pbHb9ML",
"tipo" : "test"
},
How can I do to send emails with the contents of the database?
Thanks in advance!

How to pass email receiver params in NodeJS to send email function with send grid service

I added to my NodeJS API an endpoint to send an email, for now, is a simple function that sent an email hardcoded and I did it using Send Grid service.
What I would like to achieve now is that I can pass the receiver email in the endpoint request and send the email.
Example of the endpoint url/email/:email
the :email will be the receiver of the email. I would like to pass this param to my email function which will send there. But I stack as cannot understand how to pass the param inside the sen email like it is now my code.
What I tried so far:
Router
// POST email send
router.post("/email/:email", async (req, res) => {
const email = req.params.email;
try {
const sent = await sendEmail(email);
if (sent) {
res.send({ message: "email sent successfully", status: 200 });
console.log("Email sent");
}
} catch (error) {
throw new Error(error.message);
}
});
// Routes
module.exports = router;
Send email
const mailGenerator = new MailGen({
theme: "salted",
product: {
name: "Awesome Movies",
link: "http://example.com"
}
});
const email = {
body: {
name: receiver here??,
intro: "Welcome to the movie platform",
action: {
instructions:
"Please click the button below to checkout new movies",
button: {
color: "#33b5e5",
text: "New Movies Waiting For you",
link: "http://example.com/"
}
}
}
};
const emailTemplate = mailGenerator.generate(email);
require("fs").writeFileSync("preview.html", emailTemplate, "utf8");
const msg = {
to: receiver here??,
from: "jake#email.io",
subject: "Testing email from NodeJS",
html: emailTemplate
};
const sendEmail = () => {
try {
sgMail.setApiKey(sg_token);
return sgMail.send(msg);
} catch (error) {
throw new Error(error.message);
}
};
module.exports = { sendEmail };
Your sendEmail method not accept parameters. Add receiver on signature and use it
const sendEmail = (receiver) => {
try {
sgMail.setApiKey(sg_token);
return sgMail.send({ ...msg, to: receiver });
} catch (error) {
throw new Error(error.message);
}
};

how to call a event in the dialogflow v2 :nodejs

I'm using dialogflow v2 using npm. I just want call a welcome event in dialogflow. How can I do it in the nodejs. I'm pretty new to it.
This is my code
const projectId = "xxxxxx";
const LANGUAGE_CODE = 'en-US';
const sessionId = req.body.sessionId;
var query = req.body.query;
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId,sessionId);
const request = {
session: sessionPath,
queryInput: {
text: {
text: query,
languageCode: LANGUAGE_CODE,
},
},
};
sessionClient.detectIntent(request).then(response => {
console.log('intent detected');
const result = response[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if(result.fulfillmentText) {
console.log(result.fulfillmentText);
return res.json({reply: result.fulfillmentText})
}
// if(result.intent) {
// console.log(` Intent: ${result.intent.displayName}`)
// }
else {
console.log('no intent found');
}
}).catch(err => {
console.log('error '+err);
})
As I open the chat page I just want to throw a welcome message. In order to do that, i read that i have to call the event. How can I do that? I have taken the reference from here
The Request body should be like this:
let eventName='WELCOME'; //name of the event
let request = {
session: sessionPath,
queryInput: {
event: {
name: eventName,
languageCode: 'en-US'
},
},
};
checkout- https://github.com/googleapis/nodejs-dialogflow/blob/master/samples/detect.js#L96
let me know if you find any difficulties :)
I would suggest using actions-on-google as it is much easier to build nodejs backend for dialogflow link : actions on google
And for sample project refer Number genie project
Hope this would help you.

Firebase Set the Notification Title and Body to Database Value

I think this is a fairly basic question, but I have a Firebase function file with an index.js file within. I am able to trigger a push notification when the database is updated with a new value, but just need help setting the notification's title and body to the values added in the child nodes. Here is what I have so far:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// database tree
exports.sendPushNotification = functions.database.ref('/questions/{id}').onWrite(event =>{
const payload = {
notification: {
title: //Value at /questions/{id}/question,
body: //Value at /questions/{id}/bestAnswer,
badge: '1',
sound: 'default',
}
};
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()){
const token = Object.keys(allToken.val());
console.log('token? ${token}');
return admin.messaging().sendToDevice(token, payload).then(response =>{
return null;
});
}
return null;
});
});
You can reference any value of the created object:
event.val().question
event.val().bestAnswer
Using those you can update your notification:
payload.notification.title = event.val().question;
payload.notification.body = event.val().bestAnswer;
or
const payload = {
notification: {
title: event.val().question,
body: event.val().bestAnswer,
badge: '1',
sound: 'default',
}

Resources