# Config DB and query function
const mysql = require('mysql');
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'QAZwsx@123',
database: 'blog',
multipleStatements: true
});
mysqlConnection.connect((err) => {
if (!err) {
console.log('DB Connection Established Successfully');
return true;
} else {
console.log('Connection Failed!' + JSON.stringify(err, undefined, 2));
return false;
}
});
class DB {
constructor() {
this.connection = mysqlConnection;
}
// All categories
getCategories() {
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM categories', (err, rows) => {
if (!err)
resolve(rows);
else
reject(err);
});
});
}
// Get category by id
getCategoryById(id) {
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM categories WHERE id = ?', [id], (err, rows) => {
if (!err)
resolve(rows);
else
reject(err);
});
});
}
// Add category
addCategory(category) {
return new Promise((resolve, reject) => {
this.connection.query('INSERT INTO categories SET ?', [category], (err, rows) => {
if (!err)
resolve(this.getCategories());
else
reject(err);
});
});
}
// Update category
updateCategory(id, category) {
return new Promise((resolve, reject) => {
this.connection.query('UPDATE categories SET ? WHERE id = ?', [category, id], (err, rows) => {
if (!err)
resolve(this.getCategories());
else
reject(err);
});
});
}
// Delete category
deleteCategory(id) {
return new Promise((resolve, reject) => {
this.connection.query('DELETE FROM categories WHERE id = ?', [id], (err, rows) => {
if (!err)
resolve(this.getCategories());
else
reject(err);
});
});
}
}
module.exports = DB;