Optimize API requests in Node.js

Viewed 220

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 seen in the example, I use .catch(next). But is this the correct way to do it? Shouldn't the route always print json?

So I am thinking of 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 then be something like res.status(some_status_code).json({})?

How is a simple API normally carried out in terms of error handling?

What if I, in the code, use a variable that is not defined (i.e. causing a syntax error)? Should I handle it with a JSON error or should I just make sure that I don't do sloppy coding? :-D

Also, is this the fastest way to print the json? I mean, should I use User.find().lean()? Should I do some caching? Is it even clever to store my API on a normal website or are there optimized API servers for such cases?

1 Answers

Have you try async/await function and custom response for success and error? Here the example :

responseHandler.js

// use this for success
function successResponse(message, data) {
  const success = {
    success: true,
    message: message,
    data: data
  }
  return success
}

// use this as middleware error handler
function errorResponse(err,req,res,next) => {
  return res.status(err.status || 500).json({
    success: false,
    message: err.message
  })
}

module.exports = {
  successResponse,
  errorResponse
}

myRouter.js

const { successResponse } = require('./responseHandler')

exports.getUserList = async (req, res, next) => {
  await User.find().sort({ name: 1 }).then(users => {
    res.status(200).json(
      successResponse(`data user`, users)
    )
  }).catch(err => {
    return err
  });
};
Related