nested Promise & reject - node.js

I have some problem with promise functions, my app has this structure:
- routes
- service
- db
db is a class initialized when the application start and where I created some wrapper function for insert/find/ecc..., service is a layer between the route and db, here I do most of the work. My problem is that with the code below if a user already exist I want to throw an error or reject the promise but when I try to do something like this I get
Cannot read property 'then' of undefined
where is the error?
This is my resource:
router.put('/', (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(function (hash) {
req.body.password = hash;
service.addUser(req.body)
.then((user) => {
return res.json(user);
})
.catch((err) => {
return res.json(err);
});
})
.catch((err) => {
return res.json(err);
});
});
This is the service:
getBy(query) {
return this.mongo.find(query);
}
addUser(data) {
if(!data.email) {
return Promise.reject('email_missing');
}
const self = this;
self.getBy({ email: data.email })
.then((user) => {
if(user.length) {
return Promise.reject('user_exist');
}
return self.mongo.insert(data)
})
.catch((err) => {
return Promise.reject(err);
});
}
and this is the db connection:
find(query) {
const self = this;
return new Promise((resolve, reject) => {
self.collection.find(query).toArray((err, res) => {
if (err) {
self.logger.info('Mongo::find error', err);
reject(err);
} else {
self.logger.info('Mongo::find', query);
resolve(res);
}
});
});
}
insert(data) {
const self = this;
return new Promise((resolve, reject) => {
self.collection.insert(data, (err, res) => {
if (err) {
self.logger.info('Mongo::insert error', err);
reject (err)
} else {
self.logger.info('Mongo::insert', res);
resolve(res)
}
});
});
}
many thanks!

The addUser function does not return a Promise. The code should look like this:
addUser(data) {
if (!data.email) {
return Promise.reject('email_missing');
}
const self = this;
return self.getBy({
email: data.email
})
.then((user) => {
if (user.length) {
return Promise.reject('user_exist');
}
return self.mongo.insert(data)
})
.catch((err) => {
return Promise.reject(err);
});
}
The .catch block here does not make sense because it just contains return Promise.reject(err) so you can remove it:
addUser(data) {
if (!data.email) {
return Promise.reject('email_missing');
}
const self = this;
return self.getBy({
email: data.email
})
.then((user) => {
if (user.length) {
return Promise.reject('user_exist');
}
return self.mongo.insert(data)
});
}
In the router you also have to return the Promise in the .then and you can remove one .catch block:
router.put('/', (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(function(hash) {
req.body.password = hash;
return service.addUser(req.body) // return the Promise ehre
})
// the then can be move out here, to avoid nesting
.then((user) => {
return res.json(user);
})
// only on catch is required
.catch((err) => {
return res.json(err);
});
});
An additional note, you should always reject with a real error. So it would be better to write, Promise.reject(new Error('user_exist'))

Nesting promises is an anti-pattern.
See item #2 in Promise Patterns & Anti-Patterns
It's considered an anti-pattern because it reduces understandability and overly complicates the call stack making debugging (more of) a nightmare.
So rather than:
bcrypt.hash(req.body.password, 10)
.then(function (hash) {
req.body.password = hash;
service.addUser(req.body) // ANTI-PATTERN
.then((user) => {
return res.json(user); // [1]
})
.catch((err) => {
return res.json(err); // [2]
});
})
.catch((err) => {
return res.json(err);
});
});
Do this instead:
const SALT_ROUNDS = 10
app.get(URL, function(req, res) {
function setHashedPassword() {
// TODO first test for existence of password in req.body
return bcrypt.hash(req.body.password, SALT_ROUNDS)
.then(hash => req.body.password = hash)
}
function addUser() {
return service.addUser(req.body)
}
Promise.all([ setHashedPassword(), addUser() ])
.then((results) => {
const user = results[1]
res.json(user)
})
.catch((err) => {
res.json(err)
})
})
Note that, at [1] and [2] in the OP's code, it makes no sense to return anything since there is no active context to which you can return a value.
I'd also respond with an object like:
res.json({ok:true, user:user})
and
res.json({ok:false, error:err})
So you can check for success or failure in the client.
Yes, I know you might believe that ok is redundant here, but it's good practice to standardize on a single result value so you don't have to first test for the existence of error before you check for the existence of user.

Related

convert simple callbacks into async await

I am finding it hard to convert this user controllers code to async await. Can someone please help and guide me how can i do it too. So that i can also change any callbacks into async await.
Also if someone can provide a good source so that i can read about async await and how to apply them properly.
const User = require("../models/user")
exports.getUserById = (req, res, next, id) => {
User.findById(id).exec((error, user) => {
if (error || !user) {
return res.status(400).json({
error: "No user was found in DB"
})
}
req.profile = user
next()
})
}
exports.getUser = (req, res) => {
req.profile.salt = undefined;
req.profile.encrypted_password = undefined;
return res.json(req.profile)
}
exports.getAllUsers = (req, res) => {
User.find().exec((error, users) => {
if (error || !users) {
return res.status(400).json({
error: "No users was found in DB"
})
}
return res.json(users)
})
}
exports.updateUser = (req, res) => {
User.findByIdAndUpdate(
{ _id: req.profile._id },
{ $set: req.body },
{ new: true, useFindAndModify: false },
(error, user) => {
if (error) {
return res.status(400).json({
error: "You are not authorized to update this info"
})
}
user.salt = undefined;
user.encrypted_password = undefined;
res.json(user)
}
)
}
It should look something like this:
const User = require("../models/user");
exports.getUserById = async (req, res, next, id) => {
let user = await User.findById(id);
try {
if (!user) {
return res.status(404).json({
error: "No user was found in DB"
});
}
req.profile = user;
next();
} catch (err) {
return res.status(500).json({
error: "Something went wrong"
});
}
};
exports.getUser = (req, res) => {
req.profile.salt = undefined;
req.profile.encrypted_password = undefined;
return res.json(req.profile);
};
exports.getAllUsers = async (req, res) => {
let users = await User.find();
try {
if (users.length < 1) {
return res.status(404).json({
error: "No users was found in DB"
});
}
return res.json(users);
} catch (err) {
return res.status(500).json({
error: "Something went wrong"
});
}
};
exports.updateUser = async (req, res) => {
try {
let user = await User.findByIdAndUpdate(
{ _id: req.profile._id },
{ $set: req.body },
{ new: true, useFindAndModify: false }
);
user.salt = undefined;
user.encrypted_password = undefined;
return res.json(user);
} catch (err) {
return res.status(400).json({
error: "You are not authorized to update this info"
});
}
};
You should send back 404 errors if you cant find any user in the database. 400 means bad request.
You can achieve what you are asking by wrapping the function with Promise. In your example, you should use the solution given by Ifaruki, because mongoose already supports promises.
function waitSeconds(seconds) {
return new Promise(res => {
setTimeout(() => {
res();
}, seconds * 1000)
})
}
async function foo() {
console.log("Hello");
await waitSeconds(5);
console.log("World");
}
Here you can learn more about async in javascript

Async / Await with NodeJS + Mongoose doesn't wait

Cannot get the async / await functions to work properly in my card game app.
(a) I get the 201 response with no data.
(b) the deck document seems to be created afterwards, with the players field an empty array, indicating it is done after the deck is saved to the mongoDB
Below is my code. Any help is appreciated.
router.js
router.post('/game', (req, res, next) => {
try {
const { cards, playerNames, attributes } = req.body;
const newDeck = deck.start(cards, playerNames, attributes);
res.status(201).send(newDeck);
} catch (err) {
next(err);
};
});
/services/deck.js
exports.start = async (cards, playerNames, attributes) => {
try {
const users = await user.create(playerNames);
const deck = new Deck({
cards,
attributes,
players: users
});
return await deck.save((err, newDeck) => {
if (err) console.log(err);
console.log('RESULT', newDeck);
});
} catch (err) {
console.log(err);
}
};
/services/user.js
exports.create = async (users) => {
if (users.constructor === String) {
const user = new User({displayname: users});
return await user.save((err, newUser) => {
if (err) console.log(err);
console.log('NEW USERS ', user);
return newUser;
});
} else if (users.constructor === Array) {
let userList = [];
await users.forEach(name => {
const user = new User({displayname: name.toString()});
return user.save((err, newUser) => {
if (err) {
console.log(err);
} else {
userList.push(newUser);
return newUser;
}
});
});
console.log('NEW USERS ', userList);
return userList;
};
};
I am not familiar how you're handling promises,
but forEach is not promise-aware, that's how it has been designed, so it will not handle your asynchronous code properly
replace it with normal for loop or for-of loop, and add the await keyword in front of the user.save() method

Rejected Promise Resolves in NodeJs

I'm not able to catch the rejected promise and I don't understand where I'm going wrong. Here's what I have
exports.signIn = (username, password) => {
return new Promise((resolve, reject) => {
pool.query(
"select * from user where username=? order by id asc limit 1",
[username],
(err, result, fields) => {
if (!err) {
console.log("user result: ", result);
if (result.length === 1) {
let user = result[0];
bcrypt.compare(password, user.password, (error, res) => {
if (error) {
reject(error);
}
if (res) {
console.log("user found: ",user.username);
resolve(user);
} else {
console.log("Incorrect password");
reject("Unauthorized Access");
}
});
} else {
console.log("user not found");
reject("Invalid username");
}
}
}
);
});
};
This is how I use the promise
app.post("/signin", (req, res, next) => {
let body = req.body;
let password = body.password;
let username = body.username;
db.signIn(username, password)
.catch(err => {
res.status(200).json({ err });
})
.then(result => {
console.log("signin: ", result);
res.status(200).json({ result });
});
});
When I enter a correct password, it resolves properly but when I enter a wrong password it still resolves with the signin console message and an UnhandledPromiseRejectionWarning warning. I really don't see where I'm going wrong, perhaps an extra eye will do.
You should use promise as :
app.post("/signin", (req, res, next) => {
let body = req.body;
let password = body.password;
let username = body.username;
db.signIn(username, password)
.then(result => {
console.log("signin: ", result);
res.status(200).json({ result });
}).catch(err => {
res.status(200).json({ err });
});
});
Because, after catch if you will add any number of then handling, it will execute them all.

How to separate the method to the route

I had this route and it worked perfectly
router.get('/api/User/:id',async(req,res)=>{
try {
const{id}=req.params;
let result =await pool1.request()
.input('Iduser', sql.Int, id)
.execute('GetUser')
res.json(result);
}
catch (err) {
res.json({ error: 'Does Not exist' })
}
});
But I want to separate the function and leave the route as clean as possible, try to separate it as follows but I get the following error: TypeError: one is not a function
Route
router.get('/api/User/:id', async(req,res)=>{
try {
res.json((await one(req.params.id))[0]);
} catch (err) {
console.log(err);
res.sendStatus(500);
}
})
Function
const one = async(id)=>{
return new Promise((resolve,reject)=>{
pool.request()
.input('Iduser', sql.Int, id)
.execute('User')((err,results) =>{
if(err){
return reject(err);
}
resolve(results);
});
});
}
What is my mistake, am I calling the function wrong?
to make your code cleaner you can do this :
const getUserById =async(req,res)=>{
try {
const{id}=req.params;
let result =await pool1.request()
.input('Iduser', sql.Int, id)
.execute('GetUser')
res.json(result);
}
catch (err) {
res.json({ error: 'Does Not exist' })
}
}
router.get('/api/User/:id',getUserById);
also to make it cleaner more you can do it like this
export const asyncHandler = (fn) => async (request, response, next) => {
try {
return await fn(request, response, next);
} catch (error) {
return next(error); // or response.json({ error: 'Does Not exist' })
}
};
const getUserById =async(req,res)=>{
const { params: { id } }=req;
const result =await pool1.request()
.input('Iduser', sql.Int, id).execute('GetUser');
return res.json(result);
}
router.get('/api/User/:id',asyncHandler(getUserById));
Thanks mate, I solved why he tells me that it was not a function, I was not calling it well but the way you explain it the route is much cleaner
function
const one = async(id)=>{
return new Promise((resolve,reject)=>{
pool.request()
.input('IdUser', sql.Int, id)
.execute('GetUser',(err,results)=>{
if(err){
return reject(err);
}
resolve(results);
}
)
});
}
route
router.get('api/user/:id', async(req,res)=>{
try {
let result=await m.one(req.params.id);
res.json(result);
} catch (error) {
console.log(error);
res.sendStatus(500);
}
})

Correct way to figure out what rejection a promise had?

I have an API / express router:
router.post("/signup", async function (req, res) {
try {
var user = await controllers.user.register(req.body.username, req.body.password);
req.session.user = user;
res.json(user);
} catch (e) {
res.status(500).json("DB Error");
}
});
Currently, on error, it returns 500 DB error. This is my controller:
function register(username, password) {
return new Promise((resolve, reject) => {
User.findOne({ username: username }).lean().exec((e, doc) => {
if (e) reject(e);
if (doc) {
reject("Username already exists.");
} else {
var user = new User({ username, password: hash(password) });
user.save((e) => {
if (e) reject(e);
else {
delete user.password;
resolve(user);
}
});
}
});
});
}
What's the right way to return a 400 if username already exists, and a 500 if it was a database error?
Mongoose already uses promises, the use of new Promise is promise construction antipattern.
Express doesn't have the concept of controllers, there are only route handlers and middlewares. Since register should be very aware of the way it will be used in a response, there may be no need for another level of abstraction above route handler. There will be no problem when a function has access to handler parameters and can form a response in-place.
It can be:
router.post("/signup", async function (req, res) {
try {
const { body, password } = req.body;
const user = await User.findOne({ username: username }).lean();
if (user) {
res.status(400).json("Username already exists");
} else {
...
res.json(user);
}
} catch (e) {
res.status(500).json("DB Error");
}
});
In case route handler needs to be reused in multiple places with some variations, it could be refactored to higher-order function or some other helper that is aware of original req and res parameters.
You can change the way you are rejecting the Promise. I'd suggest something like:
function register(username, password) {
return new Promise((resolve, reject) => {
User.findOne({ username: username }).lean().exec((e, doc) => {
if (e) reject(500);
if (doc) {
reject(400);
} else {
var user = new User({ username, password: hash(password) });
user.save((e) => {
if (e) reject(500);
else {
delete user.password;
resolve(user);
}
});
}
});
});
}
And in the route:
router.post("/signup", async function (req, res) {
try {
var user = await controllers.user.register(req.body.username, req.body.password);
req.session.user = user;
res.json(user);
} catch (e) {
res.status(e).json(e == 400 ? "Username already exists." : "DB Error");
}
});

Resources