简体   繁体   中英

Check if record exist before insert on Node JS database class

I made a class with a select, update and insert functions, but I would like to implement a check to see if the record exists before insert. I tried to create the logic above in the insert function, but I'm having some difficulty with the structure and syntax. Any suggestion?

 'use strict'; var User = require('../model/User.js'); exports.get_User_by_id = function(req, res) { User.getUserById(req.params.id, function(err, User) { if (err) res.send(err); res.json(User); }); }; exports.get_User_by_User_id = function(req, res) { var postedBody = [req.params.User_type, req.params.User_id]; User.getUserByIdUser(postedBody, function(err, User) { if (err) res.send(err); res.json(User); }); }; exports.add_User = function(req, res) { var new_User = new User(req.body); var postedBody = [new_User.User_type, new_User.User_id]; User.getUserByIdUser(postedBody, function(err, User) { if (err) { res.send(err); } else { if (User) { res.json(User); } else { // //handles null error if(!new_User.User_type || !new_User.User_id){ res.status(400).send({ error:true, message: 'Please provide type/id' }); } else{ User.insertUser(new_User, function(err, User) { if (err) res.send(err); res.json(User); }); } } } }); }; 

Edit 1: Following naga-elixir-jar examples, here is my full code: user.js (model)

 var now = new Date(); function ISODateString(d) { function pad(n) {return n<10 ? '0'+n : n} return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+' ' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'' } var User = function(User){ this.id = User.id; this.User_type = User.User_type; this.User_id = User.User_id; this.created_at = ISODateString(now); }; User.getUserByIdUser = function getUserByIdUser(body) { return new Promise((resolve, reject) => { sql.query("SELECT * FROM sb_Users WHERE User_type = ? AND User_id = ?", body, function (err, res) { if(err) { console.log("error: ", err); reject(err); } else{ resolve(res); } }); }) }; User.insertUser = function insertUser(newUser) { return new Promise((resolve, reject) => { sql.query("INSERT INTO sb_Users SET ?", newUser, function (err, res) { if(err) { console.log("error: ", err); reject(err); } else{ resolve(res); } }); }) }; 

User.js (Controller)

 var User = require('../model/User.js'); exports.get_User_by_User_id = async function(req, res) { var postedBody = [req.params.User_type, req.params.User_id]; try { const User = User.getUserByIdUser(postedBody); if (User.length === 0) { res.json("not existent"); } else { res.json(User); } } catch(e) { console.error(e); res.json("oops! something is wrong"); } }; exports.add_User = async function(req, res) { var new_User = new User(req.body); var postedBody = [new_User.User_type, new_User.User_id]; try { const User = await User.getUserByIdUser(postedBody); // I think sql returns an array of object if found or empty array otherwise if so use if (user.length === 0) if (User) { res.json(User); } else { if(!new_User.User_type || !new_User.User_id){ res.status(400).send({ error:true, message: 'Please provide type/id' }); } else { const newUser = await User.insertUser(new_User); res.json(newUser); } } } catch(e) { // handle error console.error(e); res.json("oops! something is wrong"); } }; 

You could use Promise to ease the complexity with callback. Since mysql does not provide Promise support, you could promisify your functions like:

// Some sample sql statement
User.getUserByIdUser = function getUserByIdUser(id) {
  return new Promise((resolve, reject) => {
    sql.query("Select * from users where id = ? ", id, function (err, res) {             
      if(err) {
        console.log("error: ", err);
        reject(err);
      }
      else{
        resolve(res);
      }
    });   
  })
};

// same with User.insertUser

In you route:

exports.add_User = async function(req, res) {
  var new_User = new User(req.body);
  var postedBody = [new_User.User_type, new_User.User_id];

  try {
    const user = await User.getUserByIdUser(postedBody)

    // I think sql returns an array of object if found or empty array otherwise if so use if (user.length === 0)
    if (user) {
      res.json(user);
    } else {
      if(!new_User.User_type || !new_User.User_id){
        res.status(400).send({ error:true, message: 'Please provide type/id' });
      } else {
        const newUser = await User.insertUser(new_User)
        res.json(newUser);
      }
    }
  } catch(e) {
    // handle error
    console.error(e);
    res.json("oops! something is wrong");
  }
};

Note: mysql2 provides promise wrapper over mysql so you could use that library instead of writing your own promise wrappers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM