Optimize API requests in Node.js
I have an API in Node.js. My routes look like
exports.getUserList = (req, res, next) => {
User.find().sort({ name: 1 }).then(users => {
res.json({
status: 'success',
users
});
}).catch(next);
};
As you can see from the example, I am using .catch(next)
. But is this the correct way to do it? Should the route always print json?
So, I am thinking about doing something like
exports.getUserList = (req, res, next) => {
User.find().sort({ name: 1 }).then(users => {
res.json({
status: 'success',
users
});
}).catch(err => {
res.json({
status: 'error',
msg: err
});
});
};
but shouldn't it be something like res.status(some_status_code).json({})
?
How is a simple API usually done in terms of error handling?
What if I use a variable in my code that is not defined (i.e. causes a syntax error)? Should I handle it with a JSON error, or should I just make sure I'm not doing sloppy coding?: - D
Also, is this the fastest way to print json? I mean, should I use User.find().lean()
? Should I be doing caching? Is it even wise to store your API on a regular website, or are there optimized API servers for such cases?
source to share
No one has answered this question yet
Check out similar questions: