NodeJS: Promise.resolve returns undefined - javascript

I am working on Password reset functionality in NodeJS and am facing Promise.resovle undefined issue. I am getting the corrrect values from the database and able to send the actual email, but the promise in the main function doesn't return anything.
Any help would be welcome.
Here is my main route function-
router.post('/reset-password', async (req, res) => {
const { email } = req.body
const emailCheck = await db.query('SELECT EXISTS (SELECT email from tickets where email=$1)', [email])
const ifExist = Object.values(emailCheck.rows[0])[0]
if (ifExist) {
const resetPin = Math.floor(100000 + Math.random() * 900000) //random 6 digit pin with 0 not as first digit
await db.query('UPDATE tickets SET pin=$1 where email=$2', [resetPin, email])
const result = await emailProcessor(email, resetPin)
console.log(result) /////returns undefined!
if (result) {
return res.status(401).json({
status: 'success',
message: 'Pin sent to email if present in our database'
})
}
}
res.status(403).json({
status: 'error',
message: 'Pin sent to email if present in our database'
})
Here is my helper function using nodemailer-
const transporter = nodemailer.createTransport({
host: 'randomhost',
port: 587,
auth: {
user: 'abc.email',
pass: '123'
}})
const sendEmail = (info) => {
return new Promise(async (resolve, reject) => {
try {
let result = await transporter.sendMail(info);
console.log("Message sent: %s", result.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(result));
resolve(result)
} catch (error) {
console.log(error)
}
})}
const emailProcessor = (email, pin) => {
const info = {
from: '"app" <email>',
to: email,
subject: "Reset Pin",
text: "Pin is " + pin,
html: `<b>Reset Pin</b><b>${pin}`,
}
sendEmail(info)}

emailProcessor doesn't currently have a return statement, so it implicitly returns undefined. Change it to:
const emailProcessor = (email, pin) => {
const info = {
from: '"app" <email>',
to: email,
subject: "Reset Pin",
text: "Pin is " + pin,
html: `<b>Reset Pin</b><b>${pin}`,
};
return sendEmail(info); // <------ added return
};
P.S, sendEmail does not need to use the promise constructor, new Promise. You're already using promises, so you just need to use the ones that are there, not make a new one.
const sendEmail = async (info) => {
try {
let result = await transporter.sendMail(info);
console.log("Message sent: %s", result.messageId);
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(result));
return result;
} catch (error) {
console.log(error);
}
};

Related

Firebase Cloud Function Unauthenticated Error After Password Sign-Up

I am receiving the following error when triggering this cloud function: "Error unauthenticated".
I do not wish to allow unauthenticated calls to this cloud function.
The workflow is as follows:
User registers in app via firebase password authentication
Firebase Auth Credentials are created (firebase signs in user upon success)
Once the credentials have been created, the cloud function is triggered in the firebase auth callback.
At this point, the call should be authenticated, given it's being triggered in the firebase auth response.
However, it keeps erroring with
Error: unauthenticated
The user is authenticated at this point.
Any suggestions?
CLIENT CODE ->
const onRegisterPress = () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
setLoading(true);
//CREATE'S USER'S AUTH CREDENTIALS
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
const data = {
...
}
//console.log(response);
return new Promise(async function(resolve, reject) {
await firebase.functions().httpsCallable('writeAccountUser')({
data
}).then((response) => {
console.log("Write Account User Response: ", response);
resolve(setLoading(false));
}).catch((error) => {
console.error("Cloud Function Error: ", error);
setLoading(false);
reject(error)
})
});
})
.catch((error) => {
alert(error)
});
}
CLOUD FUNCTION ->
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const firestore = admin.firestore();
exports.writeAccountUser = functions.https.onCall((data, context) => {
console.log("Incoming Data: ", data);
console.log("Incoming Context: ", context);
const clientData = data.data;
console.log("Client Data: ", clientData);
console.log("Account ID: ", clientData.accountID);
return new Promise(async function (resolve, reject) {
const accountsRef = firestore.collection('Accounts');
const usersRef = firestore.collection('users');
const now = new Date();
if (clientData.accountExists === true) {
console.log("Account Exists");
await accountsRef
.doc(clientData.accountID)
.update({
users: admin.firestore.FieldValue.arrayUnion(clientData.uid)
}).catch((error) => { console.error(error); reject(false) });
}
else {
console.log("Account Does Not Exist!");
const account_data = clientData.accountData;
const product_lines = clientData.productLines;
await accountsRef
.doc(clientData.accountID)
.set({
account_data,
product_lines,
users: [clientData.uid],
dateCreated: {
date: now,
timestamp: now.getTime()
}
}).catch((error) => { console.error(error); reject(false)});
};
const email = clientData.email;
const fullName = clientData.fullName;
const acceptTerms = clientData.acceptTerms;
const userData = {
id: clientData.uid,
email,
fullName,
accountID: clientData.accountID,
dateCreated: {
date: now,
timestamp: now.getTime()
},
lastUpdateFetch: {
date: now,
timestamp: now.getTime()
},
termsConditionsAccepted: acceptTerms
};
await usersRef
.doc(clientData.uid)
.set(userData)
.catch((error) => { console.error(error); reject(false) });
resolve(true);
});
});
Error ->
[Unhandled promise rejection: Error: unauthenticated]
at node_modules/#firebase/firestore/dist/rn/prebuilt.rn-f9cd27ba.js:12199:33 in
at http:///node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:169743:29 in _errorForResponse
at node_modules/#firebase/firestore/dist/rn/prebuilt.rn-f9cd27ba.js:12747:31 in yu
at node_modules/tslib/tslib.js:77:12 in
at http://REDACTED/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:120748:21 in
at http://REDACTED/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:120702:31 in fulfilled
You can try refactoring the function as shown below:
const onRegisterPress = async () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
setLoading(true);
const response = await firebase.auth().createUserWithEmailAndPassword(email, password)
const data = {...}
const fnResponse = await firebase.functions().httpsCallable('writeAccountUser')({data})
console.log("Write Account User Response: ", response);
}
You can also create the account using the Admin SDK in the same function and log the user on your web app after the response. That'll ensure the Cloud function's action has been executed as well (just in case the function is not called after user sign up for any reason).

How to connect Dialogflow Fulfillment with MySQL DB?

I tried to connect my Dialogflow agent with MySQL DB at my GCP, but it didn't work well.
I just wanna see the results in console, but there's no results about that.
I can only see the result "Undefined", but since I am not familiar with Node.js, I am not sure what this means.
Since there is no content in the result, I cannot proceed to the next step.
Here is my index.js script :
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const mysql = require('mysql');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function connectToDatabase() {
const connection = mysql.createConnection({
host: '34.64.***.***',
user: 'username',
password: 'password',
database: 'dbname'
});
return new Promise((resolve,reject) => {
connection.connect();
console.log('connection successed.');
resolve(connection);
});
}
function queryDatabase(connection, name){
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM tb_user WHERE name = ?', name, (error, results, fields) => {
console.log('query successed.');
resolve(results);
});
});
}
function queryDatabase2(connection){
return new Promise((resolve, reject) => {
connection.query('SELECT * FROM tb_user', (error, results, fields) => {
if (error) console.log(error);
console.log('results', results);
});
});
}
function handleReadFromMysql(agent) {
const user_name = agent.parameters.name;
console.log(user_name.name);
return connectToDatabase()
.then(connection => {
console.log('connectToDatabase passed');
return queryDatabase(connection, user_name.name)
//return queryDatabase2(connection)
.then(result => {
console.log('queryDatabase passed');
console.log(result);
agent.add(`User name is ${user_name} .`);
//result.map(user => {
//if(user_name === user.name) {
//agent.add(`UserID is ${user.id}`);
//}
//});
connection.end();
});
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('findName', handleReadFromMysql);
agent.handleRequest(intentMap);
});
and the logs are :
enter image description here
Please somebody help me...
I solved this problem 4 months ago, so I share my code to help another like me.
I use socketPath of DB info. I forgot the reason.
function connectToDatabase() {
const connection = mysql.createConnection({
socketPath: '/cloudsql/*************:asia-northeast3:****',
user: '****',
password: '****',
database: '****'
});
return new Promise((resolve, reject) => {
connection.connect();
console.log('connection successed.');
resolve(connection);
});
}
And make query function like :
function findNameCountQuery(connection, name) {
return new Promise((resolve, reject) => {
var sql = `SELECT * FROM tb_user WHERE name = ?`;
var execSql = connection.query(sql, [name], (error, results) => {
if (error) throw error;
resolve(results);
});
});
Then I use agent function like :
async function findName(agent) {
const user_name = agent.parameters.person.name;
const connection = await connectToDatabase();
const result = await findNameQuery(connection, user_name);
result.map(user => {
message += `사용자 ID seq number : ${user.seq}\n`;
});
agent.add(message);
connection.end();
}
Hope to be helpful.

Make query for every object in json using for or forEach

My problem is, I want to make INSERT query for every object from JSON using some loop, but I almost always got an error "Cannot set headers after they are sent to the client".Can someone help?Tnx
const connection = require('./config');
module.exports.excel = function (req, res) {
var _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
var jsonData = req.body;
var values = [];
function database() {
return new Promise((resolve, reject) => {
jsonData.forEach((value) => {
values.push([value.id, value.first_name, value.last_name]);
connection.query(_query, [values], (error, results) => {
if (error) {
reject(
res.json({
status: false,
message: error.message
}))
} else {
resolve(
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
}))
}
});
});
})
}
async function write() {
await database();
}
write();
}
After I got JSON from my Angular 6 front I put req.body into jsonData and try with forEach to put every object("value" in this case) into query and write that into Excel file.
You will have to wrap each query in a Promise and wait for all to complete before sending the response using Promise.all
Not that database() is going to throw when one of the queries fail and you won't have any access to the resolved promises.
const connection = require('./config');
module.exports.excel = function(req, res) {
const _query = 'INSERT INTO excel (id, first_name, last_name) values ?';
const jsonData = req.body;
function database() {
return Promise.all(
jsonData.map(
value =>
new Promise((resolve, reject) => {
const values = [value.id, value.first_name, value.last_name]
connection.query(_query, [values], (error, results) => {
if (error) {
reject(error.message);
return;
}
resolve(results);
});
})
)
);
}
async function write() {
try {
const results = await database();
res.json({
status: true,
data: results,
message: 'Excel file successfully created in database'
});
} catch (e) {
res.json({
status: false,
message: e.message
});
}
}
write();
};

How to migrate my mongoose PROMISE chain transactions to ASYNC / AWAIT flow?

I created an API that integrate database responses in a promise flow, but I think the interpretation of the code is complex and I believe that async / await approach could improve both understanding and the code itself.
The API is built in NodeJS using mongoose 5.6.1 and express 4.17.1.
Can you help me in improve this?
Below is the API that I want to improve:
/** New employee */
router.post('/', (req, res) => {
let { idCompany, name, departament } = req.body;
let _id = mongoose.Types.ObjectId(); // Generating new MongoDB _ID
let employeeCreated;
const promise1 = new Promise((resolve, reject) => {
// Querying by document '$oid'
Companies.findOne({ _id: idCompany }, (err, company) => {
// Error returned
if (err) reject({ error: "Invalid request, something went wrong!" });
// Invalid data received
if (!company) reject({ error: "Unauthorized action!" });
// Everything OK
resolve(company);
});
})
.then(company => {
if(company) {
const promise2 = new Promise((resolve, reject) => {
Employees.create({ _id, idCompany, name, departament }, (err, employee) => {
// Error returned
if (err) reject({ error: "Invalid request, something went wrong!", err });
// Everything OK
employeeCreated = employee;
resolve(company);
});
})
return promise2;
}else reject({ error: "Company not found!" });
})
.then(company => {
let { name: companyName, address, email, tel, employees } = company;
employees.push(_id);
const promise3 = new Promise((resolve, reject) => {
Companies.findByIdAndUpdate(
{ _id: idCompany },
{ $set: { _id: idCompany, name: companyName, address, email, tel, employees } }, // spotlight
{ new: true },
(err, company) => {
// Something wrong happens
if (err) reject({ success: false, error: "Can't update company!" });
// Everything OK
resolve(company);
}
);
});
return promise3;
});
promise1
.then(() => res.json({ success: true, employeeCreated }))
.catch(err => res.status(400).json({ error: "Invalid request, something went wrong!", err }));
});
Regards.
One key to using promises with mongoose, is using the exec method:
Your code could then look something like this (not tested):
router.post('/', async (req, res) => {
try {
const { idCompany, name, departament } = req.body;
const _id = mongoose.Types.ObjectId();
const company = await Companies.findOne({ _id: idCompany }).exec();
const employeeCreated = await Employees.create({ _id, idCompany, name, departament });
const { name: companyName, address, email, tel, employees } = company;
employees.push(_id);
await Companies.findByIdAndUpdate(
{ _id: idCompany },
{ $set: { _id: idCompany, name: companyName, address, email, tel, employees } }, // spotlight
{ new: true }).exec();
res.json({ success: true, employeeCreated });
} catch(err) {
res.status(400).json({ error: "Invalid request, something went wrong!", err });
}
});
You could throw some specific custom errors in the try block if you find that necessary.
You could simply make the functions where your promises are running async and so, you could await for the promises to resolve.
For example, in your route use this:
router.post('/', async (req, res) => {
and then when performing an async operation, use this:
const company = await Companies.findOne({ _id: idCompany }).exec();
Also, I would suggest you to wrap this with try and catch statments
Hope it helps!

Promise returns undefined json in Express post request

I have a promise within a selectRecipientData function that returns some user data from an api.
export async function selectRecipientData({ email }) {
engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
}, function(err, result) {
if(err) {
console.log(err);
} else {
let recipient = JSON.stringify(result);
// this logs successfully
console.log('Recipient details: ' + recipient );
return recipient;
}
});
}
When I call this function within a post request. The data is logged within the promise but is undefined when returned as per below:
server.post('/api/v1/public/selectrecipientdata', async (req, res) => {
formData = req.body;
let { email } = formData;
if (!email) {
res.json({ error: 'Email is required' });
return;
}
try {
let recipientData = await selectRecipientData({ email });
// why is this undefined?
console.log('This is Undefined: '+ JSON.stringify(recipientData) );
res.json({recipientData});
} catch (err) {
res.json({ error: err.message || err.toString() });
}
});
Anyone tell me why? Thanks
You've written selectRecipientData as a callback style function, but you're calling it as an async/await style. If engage.selectRecipientData returns a promise, you could do something like:
export async function selectRecipientData({email}) {
const result=await engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
});
const recipient=JSON.stringify(result);
console.log('Recipient details: ' + recipient );
return recipient;
}
Otherwise, to convert it to a promise you could do something like:
export function selectRecipientData({email}) {
return new Promise((resolve,reject)=>{
engage.selectRecipientData({
listId: listId,
email: email,
returnContactLists: false,
}, function(err, result) {
if (err) {
reject(err);
}
else {
let recipient = JSON.stringify(result);
console.log('Recipient details: ' + recipient);
resolve(recipient);
}
});
});
}

Categories

Resources