在Node JS数据库类上插入之前检查记录是否存在

时间:2019-04-18 14:43:23

标签: javascript mysql node.js express

我制作了一个带有选择,更新和插入功能的类,但是我想实现一个检查,以便在插入之前查看记录是否存在。我试图在insert函数中创建上述逻辑,但是在结构和语法上遇到了一些困难。有什么建议吗?

'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);
			  	});
			}
	  	}
	  }
	});    	
};

编辑1: 在naga-elixir-jar示例之后,这是我的完整代码: user.js(模型)

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(控制器)

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");
  }
};

1 个答案:

答案 0 :(得分:0)

您可以使用Promise来减轻回调的复杂性。由于mysql不提供Promise支持,因此您可以promisify使用以下功能:

// 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

在您的路线中:

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");
  }
};

注意:mysql2提供了mysql上的Promise包装器,因此您可以使用该库,而不必编写自己的Promise包装器。