I have sequelize orm and sqlite database. I am using node js and express js a backend technology.
But the issue we are facing is We have two unique columns in the model..
sms_count and sms_amt but when we log the error we just get unique constraint error for only one field. we want those unique errors for the both of the field.
Here is my code including model and controller with update SMS function.
SMS MODEL
const { DataTypes } = require("sequelize");
const sequelize = require("../../db/config");
const SMS = sequelize.define("SMS", {
sms_id: { // Primary key field
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
sms_count: {
type: DataTypes.INTEGER,
allowNull: false,
unique: {
msg: 'SMS count is already taken.'
},
validate: {
notNull: {
msg: "SMS count is required."
},
isInt: {
msg: "SMS count must be an integer."
},
min: {
args: [1],
msg: "SMS count must be at least 1."
},
}
},
sms_amt: {
type: DataTypes.STRING,
allowNull: false,
unique: {
msg: "AMT IS ALREADY TAKEN",
},
validate: {
notNull: {
msg: "SMS amount is required"
},
isNumeric: {
msg: "SMS amount must be a valid number"
},
isPositive(value) {
if (parseFloat(value) <= 0) {
throw new Error("SMS amount must be greater than zero");
}
}
}
},
isSMSPackActive: {
type: DataTypes.INTEGER,
defaultValue: 1,
allowNull: false,
validate: {
isIn: {
args: [[0, 1]],
msg: "isSMSPackActive must be either 0 or 1."
}
}
},
}, {
timestamps: true,
});
// Implement a manual check before saving or updating
SMS.beforeCreate(async (sms, options) => {
const exists = await SMS.findOne({
where: {
sms_count: sms.sms_count
}
});
if (exists) {
throw new Error('SMS count is already taken.');
}
});
SMS.beforeUpdate(async (sms, options) => {
const exists = await SMS.findOne({
where: {
sms_count: sms.sms_count,
sms_amt: sms.sms_amt,
sms_id: { [DataTypes.Op.ne]: sms.sms_id } // Exclude current record from check
}
});
if (exists) {
throw new Error('SMS count is already taken.');
}
});
module.exports = SMS;
SMS CONTROLLER
// Update a SMS
const updateSMS = async (req, res) => {
try {
const result = await SMS.update(req.body, {
where: { sms_id: req.params.id },
returning: true
});
res.json({ msg: "SMS updated successfully", statusCode: 0, data: result[1][0] });
} catch (error) {
if (error.name === 'SequelizeUniqueConstraintError') {
const errors = error.errors.map(err => ({
message: err.message,
field: err.path,
value: err.value
}));
const smsCountError = errors.find(err => err.field === 'sms_count');
if (smsCountError) {
return res.status(400).json({ errors: [smsCountError], statusCode: 1 });
}
const smsAmtError = errors.find(err => err.field === 'sms_amt');
if (smsAmtError) {
return res.status(400).json({ errors: [smsAmtError], statusCode: 1 });
}
} else if (error.name === 'SequelizeValidationError') {
const errors = error.errors.map(err => ({
message: err.message,
field: err.path,
value: err.value
}));
return res.status(400).json({ errors: errors, statusCode: 1 });
}
const errors = [{
message: error.message || "An unexpected error occurred",
field: null,
value: null
}];
return res.status(500).json({ errors: errors, statusCode: 1 });
}
};