Search code examples
node.jsexpressmysql2

Node/Express: API using async await


I'm new to node and wondering if I'm heading in the right direction with my usage of async/await in API design.

Currently this is just for a MVP project but I'm interested in learning good patterns.

Stack: Node, Express, MySQL (using mysql2 package)

The following is a simplified version of my endpoint and should give you an idea of what I'm doing:

  createUser = async (req, res) => {
    const name = req.body.name;
    const email = req.body.email;

    let query = 'insert into Users set name = ?, email = ?';
    const values = [name, email];
    query = mysql.format(query, values);

    let result;

    // in the project, this is abstracted
    try {
      const [rows] = await this.dbPool.execute(query);
      // do something with the result of the query. simplified eg:
      result = rows.insertId;
    } catch (err) {
      // handle error and assign appropriate value to result
    }

    res.send(result);
  };

The above code does what I want to do but I wonder if I'm committing a rookie mistake in the way in which endpoint interacts with db, that'll bite me in the future. (case of don't know what I don't know yet.) I'm not looking for general coding best practices (code above is simplified) though they're welcome.


Solution

  • It's preferable to put all code that can cause errors inside try block.

    There's no need for result temporary variable. res.send(rows.insertId) can be put directly inside try block, because any error outside won't be handled by a middleware and will result in suspended request:

      createUser = async (req, res) => {
        try {
        const name = req.body.name;
        const email = req.body.email;
    
        let query = 'insert into Users set name = ?, email = ?';
        const values = [name, email];
        query = mysql.format(query, values);
    
          const [rows] = await this.dbPool.execute(query);
          // do something with the result of the query. simplified eg:
          res.send(rows.insertId);
        } catch (err) {
          // handle error and assign appropriate value to result
        }
      };
    

    In other respects it's already good enough.