// index.js
const express = require("express");
const bodyParser = require("body-parser");
var mysql = require("mysql");
const app = express();
const port = 3000;
app.use(bodyParser.json());
var con = mysql.createConnection({
host: "localhost",
user: "jevin",
password: "2090",
// database: "testDB",
});
con.connect(function (err) {
if (err) {
console.error("Error connecting to MySQL:", err);
return;
} else {
console.log("Connected!");
con.query("CREATE DATABASE IF NOT EXISTS todolist", function (err, result) {
if (err) throw err;
con.query("USE todolist", function (err, result) {
if (err) throw err;
});
console.log("Database created");
});
}
});
// const notes = getNotes()
// console.log(notes);
app.get('/tasks', (req, res) => {
// Retrieve tasks from the database
con.query('SELECT * FROM tasks', (err, results) => {
if (err) {
console.error('Error fetching tasks:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.json(results);
}
});
});
app.post('/tasks', (req, res) => {
const { title, description } = req.body;
// Insert a new task into the database
con.query(`INSERT INTO tasks (title, description) VALUES (?, ?)`, [title, description], (err, results) => {
if (err) {
console.error('Error adding task:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else {
res.json({ id: results.insertId, title, description });
}
});
});
app.put('/tasks/:id', (req, res) => {
const taskId = req.params.id;
const { title, description } = req.body;
// Update the task in the database
con.query('UPDATE tasks SET title = ?, description = ? WHERE id = ?', [title, description, taskId], (err, results) => {
if (err) {
console.error('Error updating task:', err);
res.status(500).json({ error: 'Internal Server Error' });
} else if (results.affectedRows === 0) {
res.status(404).json({ error: 'Task not found' });
} else {
res.json({ id: taskId, title, description });
}
});
});
// // Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});