I'm currently exploring Express.js and tackling my initial endpoint creation to manage user registration. The first step involves verifying if the provided username or email address is already in use. After some investigation, I devised the following code snippet:
// Verify if user_name or email already exist
pool.query('SELECT CASE WHEN EXISTS (SELECT * FROM users WHERE user_name = $1 OR email = $2) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END', [values.user_name, values.email], (error, results) => {
if (error) {
throw error
}
if (results.rows[0].case === '1') {
console.log('User already exists, notify client accordingly');
} else {
console.log('New user - proceeding with INSERT query');
pool.query('INSERT INTO users (first_name, last_name, user_name, email, password, last_password, password_salt) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *', [values.first_name, values.last_name, values.user_name, values.email, values.password, values.password, 'tmp_salt'], (error, results) => {
if (error) {
console.error('An error occurred during insertion');
throw error;
}
console.log('Results from INSERT:', results);
res.status(201).send(`User added with user_id: ${results.rows[0].user_id}`);
});
}
});
The implementation is a work in progress, but I'm wondering if this nested methodology is the most efficient approach? Specifically, checking for user_name
and/or email
existence before executing the INSERT
statement.
What are your thoughts?