Search This Blog

2023/08/31

Repository Design Pattern

 const mysql = require('mysql');


// Repository interface
class UserRepository {
constructor(connection) {
this.connection = connection;
}

getById(id) {
return new Promise((resolve, reject) => {
this.connection.query('SELECT * FROM user WHERE id = ?', [id], (error, results) => {
if (error) {
reject(error);
} else {
resolve(results[0]);
}
});
});
}

save(user) {
return new Promise((resolve, reject) => {
this.connection.query('INSERT INTO user SET ?', user, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result.insertId);
}
});
});
}
}

// Create a connection to the MySQL database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'sangram#81',
database: 'playground'
});

connection.connect();


// Client
const userRepository = new UserRepository(connection);

const user = { id: 1, name: "Alice" };
userRepository.save(user)
.then(insertedId => {
console.log(`User inserted with ID: ${insertedId}`);
return userRepository.getById(insertedId);
})
.then(retrievedUser => {
console.log("Retrieved user:", retrievedUser);
})
.catch(error => {
console.error("Error:", error);
})
.finally(() => {
connection.end(); // Close the database connection
});

No comments:

Post a Comment