Zum Dummi
Zum Dummi

Reputation: 233

the correct way using middleware in express

hey I want to make sure if I use the correct way for middleware in my simple express app, I am trying to find the email unique for register here is my example

const isUnique = (req, res, next) => {
   User.findOne({
      where:{
        email: req.body.email
      }
   })
   .then(getUser => {
        if(getUser){
          next("/userAlreadyExist") // router
          // or can i render to to html? i am using ejs
        } else {
          next()
        }
   })
   .catch(next())
}


app.post('/register', isUnique ,(req, res) => {
    res.send(`thank you for register`)
}

I want to make sure the email already exists or no, so I want to pass it on middleware first, and get a page for isUnique, if the email already in use, I want to redirect it to next router called '/emailExist', and if it success i want to redirect it to router /success can anyone help me if that code wrong or no? just want to make sure :D

Upvotes: 0

Views: 80

Answers (1)

miyu
miyu

Reputation: 346

You have a lot of options, here are a couple.

  1. You can redirect users to specific pages based on whether or not the email exists. Within your /emailAlreadyExists and /registerSuccess routes you can render whatever templates you want or return some data.
const isUnique = (req, res, next) => {
   User.findOne({
      where:{
        email: req.body.email
      }
   })
   .then(getUser => {
        if (getUser) {
            res.redirect('/emailAlreadyExists');
        } else {
            res.redirect('/registerSuccess'); // or just call next()
        }
   })
   .catch(next("DB error"));
}
  1. Pass along the results of the db query and let your final middleware handle it:
const isUnique = (req, res, next) => {
   User.findOne({
      where:{
        email: req.body.email
      }
   })
   .then(getUser => {
        req.user = getUser;
        next();
   })
   .catch(next());
}

app.post('/register', isUnique ,(req, res) => {
    if (req.user) {
        res.send('User already exists');
    } else {
        res.send(`thank you for register`);
    }
}
  1. You can also create an error handling middleware:
const isUnique = (req, res, next) => {
   User.findOne({
      where:{
        email: req.body.email
      }
   })
   .then(getUser => {
        if(getUser){
          next("Error: user already exists"); // or some other error message/object
        } else {
          next(); // continue to next middleware
        }
   })
   .catch(next("DB error")); // handle errors throw from DB read
}


app.post('/register', isUnique ,(req, res) => {
    res.send(`thank you for register`)
}

/*
    If you call "next" with an argument, Express will skip 
    straight to this error handler route with the argument 
    passed as the "err" parameter
*/

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send(`An error occurred: ${err}`);
})

Upvotes: 2

Related Questions