Review my API Controller - javascript

I am new to javascript backend and I am currently learning to build a RESTful API using node.js, express.js, sequelize.js with MySQL as my database. I have successfully built a basic Tasks API as a test. I am looking for feedback on if I did this correctly as far as javascript best practices go within one controller. Any feedback will be appreciated.
Current Logic: User can own multiple tasks
Everything works fine. I am authenticating the users using JWT strategy in Passport.js. I am authenticating them at the router level and then I am double-checking their records in db through userid before they are allowed to make any updates or deletes to their own records. Anyways, here is the controller:
'use strict';
var jwt = require('jsonwebtoken');
var config = require('../config'),
db = require('../services/database'),
Task = require('../models/task');
var TaskController = {};
// GET ALL Tasks
TaskController.get = function (req, res) {
if (!req.user.id) {
res.json({ message: 'You are not authorized.' });
} else {
db.sync().then(function () {
return Task.findAll({ where: { userid: req.user.id } }).then(function (result) {
res.status(202).json(result);
});
});
}
}
// POST ONE Task
TaskController.post = function (req, res) {
if (!req.body.task) {
res.json({ message: 'Please provide a task to post.' });
} else {
db.sync().then(function () {
var newTask = {
userid: req.user.id,
task: req.body.task
};
return Task.create(newTask).then(function () {
res.status(201).json({ message: 'Task Created!' });
});
});
}
}
// PUT ONE Task
TaskController.put = function (req, res) {
if (!req.body.task) {
res.json({ message: 'Please provide a task to update.' });
} else {
db.sync().then(function () {
// Find task by task id and user id
Task.find({ where: { id: req.params.id, userid: req.user.id } })
.then(function (task) {
// Check if record exists in db
if (task) {
task.update({
task: req.body.task
}).then(function () {
res.status(201).json({ message: 'Task updated.' });
});
} else {
res.status(404).json({ message: 'Task not found.' });
}
});
});
}
}
// DELETE ONE Task
TaskController.delete = function (req, res) {
if (!req.params.id) {
res.json({ message: 'Please provide a task to delete.' });
} else {
db.sync().then(function () {
Task.find({ where: { id: req.params.id, userid: req.user.id } })
.then(function (task) {
if (task) {
task.destroy({ where: { id: req.params.id } })
.then(function () {
res.status(202).json({ message: 'Task deleted.' });
});
} else {
res.status(404).json({ message: 'Task not found.' });
}
});
});
}
}
module.exports = TaskController;

The TaskController.js looks good but I would suggest moving all the ORM logic (Sequelize) to a file called TaskService.js
Example -
In TaskService.js -
...
exports.delete = function() {
db.sync().then(function () {
Task.find({ where: { id: req.params.id, userid: req.user.id } })
.then(function (task) {
if (task) {
task.destroy({ where: { id: req.params.id } })
.then(function () {
res.status(202).json({ message: 'Task deleted.' });
});
} else {
res.status(404).json({ message: 'Task not found.' });
}
});
});
}
then in TaskController.js -
...
const TaskService = require('./TaskService);
...
TaskController.delete = function(req, res) {
if (!req.params.id) {
res.json({ message: 'Please provide a task to delete.' });
} else {
TaskService.delete();
}
}

One thing I'd like to call out as far as Javascript best practices would be nested promises, which is a bit of an anti-pattern. You lose the power of promise chains when you nest them, in effect creating nested callbacks. Things will start getting weird once you start trying to use .catch() blocks for error handling. A quick refactor with catch blocks might look like this, even though this is still messy because of the conditional based on the whether or not the task exists in the DB:
// PUT ONE Task
TaskController.put = function (req, res) {
if (!req.body.task) {
res.json({ message: 'Please provide a task to update.' });
} else {
db.sync()
.then(function () {
// Find task by task id and user id
// NOTE: we return the promise here so that we can chain it
// to the main promise chain started by `db.sync()`
return Task.find({ where: { id: req.params.id, userid: req.user.id } });
})
.then(function (task) {
// Check if record exists in db
if (task) {
task.update({ task: req.body.task })
.then(function () {
res.status(201).json({ message: 'Task updated.' });
})
.catch(function (updateError) {
// do something with your update error
// catches an error thrown by `task.update()`
});
} else {
res.status(404).json({ message: 'Task not found.' });
}
})
.catch(function (promiseChainError) {
// do something with your promiseChainError
// this catch block catches an error thrown by
// `db.sync()` and `Task.find()`
});
}
}
Alternatively, if you're more comfortable with synchronous style code and have the option of updating your node version to v7+, this is what your functions might look like using async/await:
// PUT ONE Task
TaskController.put = async function (req, res) {
if (!req.body.task) {
res.json({ message: 'Please provide a task to update.' });
} else {
try {
await db.sync();
const task = await Task.find({ where: { id: req.params.id, userid: req.user.id } });
// Check if record exists in db
if (task) {
await task.update({ task: req.body.task });
res.status(201).json({ message: 'Task updated.' });
} else {
res.status(404).json({ message: 'Task not found.' });
}
} catch (error) {
// do some something with your error
// catches all errors thrown by anything in the try block
}
}
}
There's plenty of resources out there about promise chains and handling async methods. Check this one out in particular: http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/

Related

Error in updating profile with image using mongoose and cloudinary

updateProfile: async function(req, res) {
try {
const update = req.body;
const id = req.params.id;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
const image = req.files.profileImage;
const cloudFile = await upload(image.tempFilePath);
const profileImage = cloudFile.url
console.log('Loging cloudfile', profileImage)
await User.updateOne(id, { update }, { profileImage }, { new: true },
function(err, doc) {
if (err) {
console.log(err)
}
if (doc) {
return res.status(200).send({ sucess: true, msg: 'Profile updated successful' })
}
});
} catch (error) {
res.status(500).json({ msg: error.message });
}
}
But I'm getting an error of "Callback must be a function, got [object Object]"
I have tried to $set: update and $set: profileImage but still not working.
So the image successful upload into the cloudinary but the update for mongoose is not working.
Upon brief research into the issue, I think you are feeding the arguments in wrong. Objects can be confusing but not to worry.
Your code is:
await User.updateOne(id, { update }, { profileImage }, { new: true }
However, I believe it should be something more like:
await User.updateOne({id: id}, { profileImagine: profileImage, new: true },
The API reference annotates use of the function as:
const filter = { name: 'John Doe' };
const update = { age: 30 };
const oldDocument = await User.updateOne(filter, update);
oldDocument.n; // Number of documents matched
oldDocument.nModified; // Number of documents modified

Node JS throwing cannot set headers after they are sent to the client, after using mongoose.removeOne

I have a method that deletes products and before it does it check if the user who is trying to delete the product is the user who created it. When i execute it with Insomnia it successfully removes the product but i get an error on the console saying cannot set headers after they are sent to the client.
My method:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, () => {
return res.status(401).json("Not authorized");
})
.then(() => {
return res.status(200).json("Product deleted");
})
.catch((err) => {
return res.status(500).json({
error: err,
});
});
};
I'm pretty sure this is happening because I'm chaining a .then() and .catch() after executing it.
I tried to do this but it didn't work because the err parameter that I'm sending to the callback function is null.:
exports.deleteProduct = (req, res) => {
const id = req.params.productId;
Product.deleteOne({ _id: id, userId: req.user._id }, (err) => {
if (err) {
return res.status(401).json("Not authorized");
}
return res.status(200).json("Product deleted");
});
};
When i tried this second approach I always got the 200 status, meanwhile the product didn't delete.
Any idea how to deal with this?
You can try something like this:
Product.deleteOne({ _id: id, userId: req.user._id }, (err, result) => {
if(err) {
return "something"
}
return "something else"
});
or: in async / await way
try {
await Product.deleteOne({ _id: id, userId: req.user._id });
} catch (err) {
// handle error here
}
By the way, why you are passing userId at the deleteOne method?

Handling errors in Express.js in service / controller layers

I am writing an application in Express.js with a separate controller layer and a service layer. Here is my current code:
user.service.js
exports.registerUser = async function (email, password) {
const hash = await bcrypt.hash(password, 10);
const countUser = await User.countDocuments({email: email});
if(countUser > 0) {
throw ({ status: 409, code: 'USER_ALREADY_EXISTS', message: 'This e-mail address is already taken.' });
}
const user = new User({
email: email,
password: hash
});
return await user.save();
};
exports.loginUser = async function (email, password) {
const user = await User.findOne({ email: email });
const countUser = await User.countDocuments({email: email});
if(countUser === 0) {
throw ({ status: 404, code: 'USER_NOT_EXISTS', message: 'E-mail address does not exist.' });
}
const validPassword = await bcrypt.compare(password, user.password);
if (validPassword) {
const token = jwt.sign({ email: user.email, userId: user._id }, process.env.JWT_KEY, { expiresIn: "10s" });
return {
token: token,
expiresIn: 3600,
userId: user._id
}
} else {
throw ({ status: 401, code: 'LOGIN_INVALID', message: 'Invalid authentication credentials.' });
}
};
user.controller.js
exports.userRegister = async function (req, res, next) {
try {
const user = await UserService.registerUser(req.body.email, req.body.password);
res.status(201).json({ data: user });
} catch (e) {
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
}
}
exports.userLogin = async function (req, res, next) {
try {
const user = await UserService.loginUser(req.body.email, req.body.password);
res.status(200).json({ data: user });
} catch (e) {
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
}
}
The code works, but requires some corrections. I have a problem with error handling. I want to handle only some errors. If another error has occurred, the 500 Internal Server Error will be returned.
1) Can I use "throw" object from the service layer? Is this a good practice?
2) How to avoid duplication of this code in each controller:
if(!e.status) {
res.status(500).json( { error: { code: 'UNKNOWN_ERROR', message: 'An unknown error occurred.' } });
} else {
res.status(e.status).json( { error: { code: e.code, message: e.message } });
}
3) Does the code require other corrections? I'm just learning Node.js and I want to write the rest of the application well.
Yes, you can throw errors from service layer, it is good practice to catch errors with try/catch block in controller
I handle this with a custom error middleware, just use a next function in a catch block.
catch (e) {
next(e)
}
Example of error middleware (for more info check docs, fill free to move a middleware to file)
app.use(function (err, req, res, next) {
// err is error from next(e) function
// you can do all error processing here, logging, parsing error messages, etc...
res.status(500).send('Something broke!')
})
From my point of view it looks good. If you looking for some best practice and tools, try eslint (with AirBnb config for example) for linting, dotenv for a environment variables management, also check Node.js Best Practice
i want to give you an example:
this code in your controller
findCar(idCar)
} catch (error) {
switch (error.message) {
case ErrorConstants.ELEMENT_NOT_FOUND('LISTING'): {
return {
response: {
message: ErrorMessages.ELEMENT_NOT_FOUND_MESSAGE('LISTING'),
},
statusCode,
}
}
default: {
return {
response: {
message: ErrorMessages.UNKNOWN_ERROR_MESSAGE,
},
statusCode,
}
}
}
}
and this code in your service
findCar: async listingId => {
try {
if (some condition) {
throw new Error(ErrorConstants.ELEMENT_NOT_FOUND('LISTING'))
}
return { ... }
} catch (error) {
console.error(error.message)
throw new Error(ErrorConstants.UNKNOWN_ERROR)
}
},
controller is going to catch the service's errors

How can I repair my code? Warning: a promise was created

For some time now I have such a mistake in the console and I do not really understand what is going on and how I should fix it. Error:
can someone show me how to write it better?
Warning: a promise was created in a handler at /Users/pietrzakadrian/Desktop/bankApplicationOfficial/server/controllers/user.controller.js:119:16 but was not returned from it, see
at Function.Promise.attempt.Promise.try (/Users/pietrzakadrian/Desktop/bankApplicationOfficial/node_modules/bluebird/js/release/method.js:29:9)
and this is my code and I added a comment to the line where there is supposed to be a mistake?
// Login Action
exports.login = (req, res) => {
function getTodayDate() {
const today = new Date();
return today;
}
function getToken(userId) {
const token = jwt.sign(
{
id: userId,
},
env.SECRET_KEY,
{
expiresIn: '60min',
},
);
return token;
}
User.findOne({
where: {
login: req.body.login,
},
})
.then(isUser => {
if (isUser) {
if (bcrypt.compareSync(req.body.password, isUser.password)) {
User.update( // <- this
{
last_present_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() => {
res.status(200).json({
success: true,
token: getToken(isUser.id),
});
});
} else {
User.update(
{
last_failed_logged: getTodayDate(),
},
{ where: { login: req.body.login } },
).then(() => {
res.status(200).json({
error: 'Auth failed. The password is incorrect.',
success: false,
});
});
}
} else {
res
.status(200)
.json({ error: 'Auth failed. User does not exist', success: false });
}
})
.catch(() => {
/* just ignore */
});
};
Bluebird's documentation (check out the examples at : Warning explanations section says :
This usually means that you simply forgot a return statement somewhere, which will cause a runaway promise that is not connected to any promise chain.

Using Multiple FindOne in Mongodb

I am trying to extend the amount of fields that our API is returning. Right now the API is returning the student info by using find, as well as adding some information of the projects by getting the student info and using findOne to get the info about the project that the student is currently registered to.
I am trying to add some information about the course by using the same logic that I used to get the project information.
So I used the same findOne function that I was using for Projects and my logic is the following.
I created a variable where I can save the courseID and then I will put the contents of that variable in the temp object that sending in a json file.
If I comment out the what I added, the code works perfectly and it returns all the students that I require. However, when I make the additional findOne to get information about the course, it stops returning anything but "{}"
I am going to put a comment on the lines of code that I added, to make it easier to find.
Any sort of help will be highly appreciated!
User.find({
isEnrolled: true,
course: {
$ne: null
}
},
'email pantherID firstName lastName project course',
function(err, users) {
console.log("err, users", err, users);
if (err) {
return res.send(err);
} else if (users) {
var userPromises = [];
users.map(function(user) {
userPromises.push(new Promise(function(resolve, reject) {
///////// Added Code START///////
var courseID;
Course.findOne({
fullName: user.course
}, function(err, course) {
console.log("err, course", err, course);
if (err) {
reject('')
}
courseID = course ? course._id : null
//console.log(tempObj)
resolve(tempObj)
}),
///// ADDED CODE END //////
Project.findOne({
title: user.project
}, function(err, proj) {
console.log("err, proj", err, proj);
if (err) {
reject('')
}
//Course ID, Semester, Semester ID
//map to custom object for MJ
var tempObj = {
email: user.email,
id: user.pantherID,
firstName: user.firstName,
lastName: user.lastName,
middle: null,
valid: true,
projectTitle: user.project,
projectId: proj ? proj._id : null,
course: user.course,
courseId: courseID
}
//console.log(tempObj)
resolve(tempObj)
})
}))
})
//async wait and set
Promise.all(userPromises).then(function(results) {
res.json(results)
}).catch(function(err) {
res.send(err)
})
}
})
using promise could be bit tedious, try using async, this is how i would have done it.
// Make sure User, Course & Project models are required.
const async = require('async');
let getUsers = (cb) => {
Users.find({
isEnrolled: true,
course: {
$ne: null
}
}, 'email pantherID firstName lastName project course', (err, users) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findCourse = (users, cb) => {
async.each(users, (user, ecb) => {
Project.findOne({title: user.project})
.exec((err, project) => {
if (!err) {
users[users.indexOf(user)].projectId = project._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
let findProject = (users, cb) => {
async.each(users, (user, ecb) => {
Course.findOne({fullName: user.course})
.exec((err, course) => {
if (!err) {
users[users.indexOf(user)].courseId = course._id;
ecb();
} else {
ecb(err);
}
});
}, (err) => {
if (!err) {
cb(null, users);
} else {
cb(err);
}
});
};
// This part of the code belongs at the route scope
async.waterfall([
getUsers,
findCourse,
findProject
], (err, result) => {
if (!err) {
res.send(result);
} else {
return res.send(err);
}
});
Hope this gives better insight on how you could go about with multiple IO transactions on the same request.

Categories

Resources