Node.js 如何改进池上的错误处理
我已经创建了一个类User,它将保存将新用户插入postresql数据库的逻辑。我的代码工作得很好,但我认为它写得很差,我想了解一些如何改进它的观点,特别是错误处理Node.js 如何改进池上的错误处理,node.js,postgresql,express,Node.js,Postgresql,Express,我已经创建了一个类User,它将保存将新用户插入postresql数据库的逻辑。我的代码工作得很好,但我认为它写得很差,我想了解一些如何改进它的观点,特别是错误处理 const pool = require('../config/config.js'); // user constructor class User { constructor(user) { this.username = user.username; this.email = user.email;
const pool = require('../config/config.js');
// user constructor
class User {
constructor(user) {
this.username = user.username;
this.email = user.email;
this.password = user.password;
this.role = user.role;
}
// save new user in databes
createUser(res) {
pool.connect((err, client, done) => {
done();
if (err) return res.status(400).json({ err });
client.query('INSERT INTO users (username, email, password, role) VALUES($1, $2, $3, $4)', [this.username, this.email, this.password, this.role], (error) => {
if (error) return res.json({ error });
return res.json({ message: 'created successfully' });
});
});
}
}
module.exports = User;
app.post('/', (req, res) => {
const user = new User({
username: 'Femoz',
password: '1234',
role: 'admin',
email: 'femoz@gmail.com',
});
user.createUser(res);
// res.json('user created successfully');
});
那个
done()
调用看起来是错误的。“我假设done()的结果没有定义”-最好不要猜测,只要写(err,res)=>{done();cb(err,id:res&&res.rows[0].id);}
是的,我同意。更好:)
const pool = require('../config/config.js');
class User {
constructor(user) {
this.username = user.username;
this.email = user.email;
this.password = user.password;
this.role = user.role;
}
// save new user in databes
save(cb) {
const user = this;
// Perhaps, you should to do some checks of props e.g. a name is not empty
if (!user.name)
return cb(Error('Empty name'));
// I think that you should implement some wrapper
// e.g. `db.run` to avoid call the pool directly each time.
pool.connect((err, client, done) => {
// done(); here is an error. You released the db-connection too early.
if (err)
return cb(err);
// I assumed that the result of done() is undefined so cb will be called.
// Overwise use `&&` instead `||`.
client.query(
'INSERT INTO users (username, email, password, role) VALUES($1, $2, $3, $4) RETURNING id',
[user.username, user.email, user.password, user.role],
(err, res) => done() || cb(err, id: res && res.rows[0].id)
);
});
}
}
module.exports = User;
app.post('/', (req, res, next) => {
const user = new User({
username: 'Femoz',
password: '1234',
role: 'admin',
email: 'femoz@gmail.com',
});
// Return new id is better than a static text :)
user.save((err, id) => err ? res.status(400).json({error: err.message}) : res.json({id}));
// OR
// For Express you can pass error to an error handler
user.save((err, id) => err ? next(err) : res.json({id}));
});