Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to NodeJS and Cloud Functions for Firebase, and my website (built in ReactJS) is connected to the Firebase Realtime Database - when customer orders a product all the data he writes in html inputs become stored in my Firebase database.
Now I want to automatically send email containing that data.
From: test#mail.com
Subject: New order for you
Name: "Bla bla"
Product: "Blaa"
you get the point.
I suppose Cloud Functions for Firebase is the answer, could someone help me? What code should I implement in functions/index.js?
EDIT: This is the JSON data from my database:
{
"Email_Message" : {
"-LOOFLA-OFkKY_6Ut03b" : {
"email" : "",
"message" : "",
"name" : ""
}
}
}
Have a look at this official sample from the "Cloud Functions for Firebase Sample Library": https://github.com/firebase/functions-samples/tree/Node-8/email-confirmation
In this sample, the Cloud Function is triggered each time a new node is written (and modified) under the /users main node. You should adapt this path to your own data structure.
Also note that the event handler that is used in the sample is onWrite(), "which triggers when data is created, updated, or deleted in the Realtime Database". If you want to trigger the email sending only when an order is created, you may use the onCreate() handler, see the doc: https://firebase.google.com/docs/functions/database-events
Update, based on your update with the database structure.
Based on your structure you should adapt the Cloud Function sample code as follows:
'use strict';
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
// Configure the email transport using the default SMTP transport and a GMail account.
// For other types of transports such as Sendgrid see https://nodemailer.com/transports/
// TODO: Configure the `gmail.email` and `gmail.password` Google Cloud environment variables.
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: gmailEmail,
pass: gmailPassword,
},
});
exports.sendEmailConfirmation = functions.database.ref('/Email_Message/{mailId}').onWrite(async (change) => {
const snapshot = change.after;
const val = snapshot.val();
const mailOptions = {
from: '"......" <youremail#xxxxxxxxx.com>',
to: val.email,
};
// Building Email message.
mailOptions.subject = 'Dear ' + val.name; //for example
mailOptions.text = val.message;
try {
await mailTransport.sendMail(mailOptions);
console.log('email sent to:', val.email);
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
Related
Just started using the Realm MongoDB and i watched this video https://www.youtube.com/watch?v=Evp3xTzWCu4 from MongoDB and followed exactly what he did, but for some the function on the client side is not working. I'm using Expo React Native
I have this simple Realm function
exports = function(arg){
var collection = context.services.get("mongodb-atlas").db("questiondb").collection("questions");
collection.insertOne({name:arg}).then((doc) => {
console.log('Success')
}).catch(error=>console.log(error))
};
When i call it in the real console, it works fine.
This is the front end function
const connectDB = async () => {
const appID = "myapp-ckwfl";
const app = new Realm.App({ id: appID });
const credentials = Realm.Credentials.anonymous();
try {
const user = await app.logIn(credentials);
await user.functions.addQuestion("Myself");
console.log("Logged in");
} catch (error) {
console.log(error);
}
};
I'm getting the 'Logged in' in the console.
I went to check the activity log on the MongoDB atlas and it shows OK to both login and function
However, the function log shows me this message
[ "FunctionError: can't find a table mapping for namespace questiondb.questions" ] { "name": "addQuestion" }
And i have the database 'questiondb' with the collection 'questions'.
What am i missing here?
I ran into a similar error. The problem was that my BSON did not contain an "_id" field. But the BSON validation when saving it allowed me to save the schema like that. But when querying data through graphql I got this exact same error. So the solution was to fix the BSON schema. Even if the BSON schema saves and deploys successfully it can still be that it will not work for graphql.
You can see if your BSON has errors by navigating here:
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I have ploblems with English. I apologize in advance.
Problems with firestore and auth
Error: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
NativeFirebaseError: [firestore/permission-denied] The caller does not have permission to execute the specified operation.
My rules in FireStore:
rules_version = '2';
service cloud.firestore {
match/databases/{database}/documents {
match /Users/{document=**} {
allow read, get: if true;
allow create, update: if request.auth.uid == resource.id;
}
}
I using npm package:
#react-native-firebase/app
#react-native-firebase/app-check
#react-native-firebase/auth
#react-native-firebase/firestore
My code:
import auth from '#react-native-firebase/auth';
import firestore from '#react-native-firebase/firestore';
async function onAuthChanged(onChange) {
auth().onAuthStateChanged(onChange);
}
async function authenticateUser(status) {
if (status) {
const uid = status.uid;
let user = await firestore().collection('Users').doc(uid).get(); // Error
return ({
user: {...user.data(), uid} ?? {login: undefined, birthday: undefined, uid}
});
} else {
return { user: null };
}
}
onAuthChanged(async (status) => {
const { user } = await authenticateUser(status);
});
P.S. In fireStore my rules work: enter image description here
P.S.S. This is my first time working with Firebase and everything worked for the first two weeks with standard rules, but today it gives an error. and I do not know why. Although they offer me to put true on all the rules. This does not help in any way for 6-7 hours I have been trying to understand, so I have already turned here.
In firestore, if you got any permission denied. This is because firestore security rules.
Change your rules to:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
I've been trying to save data from my form in my MongoDB for some time.
I also get a response from the database.
See also: create object in mongo db api onclick sending form
Unfortunately there are not enough tutorials in my mother tongue and I don't seem to understand everything in English.
I've tried some of the documentation, but I always fail.
What is missing in my webhook function so that the form data can be stored?
exports = function(payload) {
const mongodb = context.services.get("mongodb-atlas");
const mycollection = mongodb.db("created_notifications").collection("dpvn_collection");
return mycollection.find({}).limit(10).toArray();
};
The Webhookfunction was totally wrong.
READ THE DOCUMENTATION FIRST
exports = function(payload, response) {
const mongodb = context.services.get("mongodb-atlas");
const requestLogs = mongodb.db("created_notifications").collection("dpvn_collection");
requestLogs.insertOne({
body: EJSON.parse(payload.body.text()),
query: payload.query
}).then(result => {
})
};
I got a schema looking something like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Schema
const PhoneNumbersSchema = new Schema({
phone_numbers: {
phone_number: 072382838232
code: ""
used: false
},
});
module.exports = PhoneNumbers = mongoose.model(
"phonenumbers",
PhoneNumbersSchema
);
And then I got an end-point that gets called from a 3rd party application that looks like this:
let result = await PhoneNumbers.findOneAndUpdate(
{ country_name: phoneNumberCountry },
{ $set: {"phone_numbers.$[elem1].services.$[elem2].sms_code": 393} },
{ arrayFilters: [ { "elem1.phone_number": simNumberUsed }, { "elem2.service_name": "steam" } ] },
Basically the end-point updates the "code" from the phone numbers in the database.
In react this is how I retrieve my phone numbers from the state:
const phonenumbers_database = useSelector((state) => {
console.log(state);
return state.phonenumbers ? state.phonenumbers.phone_numbers_details : [];
});
Every time the code gets changed in my database from the API call I would like to update "phonenumbers_database" in my state automatically.
How would I be able to do that?
MongoDB can actually watch for changes to a collection or a DB by opening a Change Stream.
First, you would open up a WebSocket from your React app to the server using something like Socket.io, and then watch for changes on your model:
PhoneNumbers
.watch()
.on('change', data => socket.emit('phoneNumberUpdated', data));
Your third party app will make the changes to the database to your API, and then the changes will be automatically pushed back to the client.
You could do a polling and check the Database every N secs or by using change streams
After that, to notify your frontend app, you need to use WebSockets, check on Socket IO
I'm implementing a watson conversation chat, now i'm wondering, how i can import this chat in a existing website?
any helps?
You can see one example conversation-simple in Nodejs and Conversation-with-discovery in Java.
This repository it is from IBM Developers.
This example show one example how to call the API and has some front-end for show the conversation flow and Watson understands, all you have to know how to use Watson, context variables, intents, entities, etc.
In this case, you call conversation API with Service Credentials and Workspace_id from your Conversation created inside IBM Bluemix:
Example to call and invoke the result with Javascript language (nodejs):
var conversation = new Conversation({
// If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
// username: '<username>', paste the Service Credentials here or paste in env archive
// password: '<password>',
url: 'https://gateway.watsonplatform.net/conversation/api',
version_date: '2016-10-21',
version: 'v1'
});
// Endpoint to be call from the client side
app.post('/api/message', function(req, res) {
var workspace = process.env.WORKSPACE_ID || '<workspace-id>'; //workspace id can be check inside Conversation Service, click View details
if (!workspace || workspace === '<workspace-id>') {
return res.json({
'output': {
'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable.' //error if workspace_id is not set
}
});
}
var payload = {
workspace_id: workspace,
context: req.body.context || {},
input: req.body.input || {}
};
// Send the input to the conversation service
conversation.message(payload, function(err, data) {
if (err) {
return res.status(err.code || 500).json(err);
}
return res.json(updateMessage(payload, data));
});
});
You can use other languages (Python, curl, Java) see this Documentation.
Check the example here running.