exports.signup = async (req, res) => {
const { username, password, name } = req.body;
// TODO: Validate if username exists
await knex("users").insert({ username, password, name });
const user = await knex("users").where({ username }).first();
// const users = await knex("users").where({username});
// if (users === username) {
// res.status(401).json({
// error: {
// message: "Username already exists"
// }
// })
// } else {
const token = jwt.sign({ username, id: user.id }, secret);
console.log(token);
res.json({ ...user, token });
// }
};
I can’t throw an error when I enter username which already exist in database mySQL. It keeps crashing the server and doesn;t reach else
It keeps crashing the server and doesn’t reach else.
exports.up = function (knex) {
return knex.schema.createTable("users", (table) => {
table.increments('id').primary();
table.string("username").notNullable().unique();
table.string("password").notNullable();
table.string("name").notNullable();
});
};
exports.down = function (knex) {
return knex.schema.dropTable("users");
};
username is unique.
2
Answers
You can
try - catch
and analize the error code to see if it represents a unique key constraint violation in mySQL:Create
unique
constraint onusername
field in database.ALTER TABLE users ADD UNIQUE (username);
And try again with same username it will throw error of duplicate entry.