Home > OS >  Where should data-validation happen using Express (and MySQL)?
Where should data-validation happen using Express (and MySQL)?

Time:02-27

I'm currently learning MySQL by creating an REST API using Express. I've opted for validating data on the server instead of the database. My question is, WHERE on the server should I do that? Should I validate data (for example minimum and maximum length for the username)...

  • ...using a middleware before the controller file?
  • ...in the controller file, after reciving the request and before sending the data to the models file? (example file below)
  • ...the models file before querying? (example file below)
  • ...some completely other solution I haven't thought of?

./controllers/authController.js

const register = async (req, res) => {
  const { username, email, password } = req.body;

    **// Validating input data here?**

  // TODO hash password
  const activationToken = generateActivationToken(48);
  const newUser = await User.create(
    { username, email, password, activationToken },
    (err, result) => {
      console.log(err);
      if (err)
        return res.status(400).json({
          msg: err.message || "Some error has occured. Please try again.",
        });
      else res.json({ result });
    }
  );
};

./models/User.js

var db = require("../dbconnection");

// constructor for User object
const User = function (user) {
  this.username = user.username;
  this.email = user.email;
  this.password = user.password;
  this.activationToken = user.activationToken;
};

User.create = (newUser, result) => {

**// Validating input data here?**

  db.query("INSERT INTO users SET ?", newUser, (err, res) => {
    if (err) return result(err, null);

    console.log("Created user.");
    result(null, { id: res.insertId });
  });
};

module.exports = User;

What's the usual/best practice way of doing this? If there isn't a best practice, how do YOU do it? (I validate data on the front-end too of course.) Do you know of any good example projects I could take a look at?

Thank you for your time!

CodePudding user response:

In OOP there's a principle called as:

"The information Expert principle"

According to this principle we should assign responsibilities / methods inside the objects that contain the most information to fulfil the task (It helps us create cohesive classes).

So, you should probably put the validation logic inside the User model.

  • Related