Question

To Put My Question In Better Context...

I am about done writing my first real-world Node application, which would be classified as a REST API. For myself, it was a bit challenging to wrap my head around Node's Async event processing. I still don't think I fully grasp it, as you will see by the specifics of this post. That being said...

Am I Making This Overly Complicated?

I found some code snippets online that helped me get my API working. Below is one function that deals with finding a client. I guess you would call the file this is in, a Controller, for those of you familiar with MVC. But this being Node, and NOT MVC, my question is this:

GET http://localhost/clients/3 -> brings me to this code...

// Find a single client with a Id
exports.findOne = (req, res) => {
  Client.findById(req.params.clientId, (err, data) => {
    if (err) {
      if (err.kind === "not_found") {
        res.status(404).send({
          message: `Not found Client with id ${req.params.clientId}.`
        });
      } else {
        res.status(500).send({
          message: "Error retrieving Client with id " + req.params.clientId
        });
      }
    } else res.send(data);
  });
};

What is the reason for this call to have a callback itself???

Client.findById(req.params.clientId, (err, data) => {

which in turn, looks like this:

Client.findById = (clientId, result) => {
  sql.query(`SELECT * FROM clients WHERE id = ${clientId}`, (err, res) => {
    if (err) {
      console.log("error: ", err);
      result(err, null);
      return;
    }

    if (res.length) {
      console.log("found client: ", res[0]);
      result(null, res[0]);
      return;
    }

    // not found client with the id
    result({ kind: "not_found" }, null);
  });
};

This seems like a lot of work for a simple query function. Coming from a PHP background, this could be done in very few lines of code there.

The whole thing seems complicated. Is all this really necessary for such a simple API that returns a client record of only four columns?

For that matter, do I even need that intermediate function (controller)? What's the matter with just routing right to the final function (in this case, a function named findById ) ??

I'd sure appreciate some input on this before I get too far ahead. I have another dozen endpoints to code, so if I need to change directions, now would be the time.

Thanks!

Était-ce utile?

La solution

Yeah it does look odd. try using Promises

try
{
    await data = Client.findbyId(id)
    console.log("worked");
{
catch(e)
{
    //error handling
}
Licencié sous: CC-BY-SA avec attribution
scroll top