119 lines
2.7 KiB
JavaScript
119 lines
2.7 KiB
JavaScript
const { Sequelize, DataTypes } = require("sequelize");
|
|
|
|
const sequelize = new Sequelize("Demo", "postgres", "password", {
|
|
host: "localhost",
|
|
dialect: "postgres",
|
|
});
|
|
|
|
const Student = sequelize.define(
|
|
"Student",
|
|
{
|
|
Id: {
|
|
type: DataTypes.INTEGER,
|
|
primaryKey: true,
|
|
autoIncrement: true,
|
|
},
|
|
Name: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
Age: {
|
|
type: DataTypes.INTEGER,
|
|
allowNull: false,
|
|
},
|
|
Email: {
|
|
type: DataTypes.STRING,
|
|
allowNull: false,
|
|
},
|
|
Phone: {
|
|
type: DataTypes.BIGINT,
|
|
allowNull: true,
|
|
},
|
|
},
|
|
{
|
|
tableName: "student_data",
|
|
timestamps: false,
|
|
}
|
|
);
|
|
|
|
const connectDatabase = async () => {
|
|
try {
|
|
await sequelize.authenticate();
|
|
console.log("Connected to the PostgreSQL database successfully.");
|
|
await Student.sync()
|
|
} catch (error) {
|
|
console.error("Unable to connect to the database:", error);
|
|
}
|
|
};
|
|
connectDatabase();
|
|
|
|
const getUsers = async (req, res) => {
|
|
try {
|
|
const students = await Student.findAll();
|
|
res.status(200).json(students);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
};
|
|
|
|
const getUserById = async (req, res) => {
|
|
try {
|
|
const student = await Student.findByPk(req.params.id);
|
|
if (student) {
|
|
res.status(200).json(student);
|
|
} else {
|
|
res.status(404).json({ error: "Student not found" });
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
};
|
|
|
|
const createUser = async (req, res) => {
|
|
try {
|
|
const { Name, Age, Email } = req.body;
|
|
const newStudent = await Student.create({ Name, Age, Email });
|
|
res.status(201).json({ message: `User added with ID: ${newStudent.Id}` });
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
};
|
|
|
|
const updateUser = async (req, res) => {
|
|
try {
|
|
const { Name, Age, Email } = req.body;
|
|
const [updated] = await Student.update(
|
|
{ Name, Age, Email },
|
|
{ where: { Id: req.params.id } }
|
|
);
|
|
if (updated) {
|
|
res.status(200).json({ message: `User modified with ID: ${req.params.id}` });
|
|
} else {
|
|
res.status(404).json({ error: "Student not found" });
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
};
|
|
|
|
const deleteUser = async (req, res) => {
|
|
try {
|
|
const deleted = await Student.destroy({ where: { Id: req.params.id } });
|
|
if (deleted) {
|
|
res.status(200).json({ message: "Data deleted successfully." });
|
|
} else {
|
|
res.status(404).json({ error: "Student not found" });
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
getUsers,
|
|
getUserById,
|
|
createUser,
|
|
updateUser,
|
|
deleteUser,
|
|
};
|