38 lines
1.2 KiB
JavaScript
38 lines
1.2 KiB
JavaScript
const mysql = require('mysql')
|
|
|
|
module.exports = function rewardRedemption(user_id, user_name) {
|
|
// Create a connection to the MySQL database
|
|
const connection = mysql.createConnection({
|
|
host: process.env.MYSQL_HOST,
|
|
user: process.env.MYSQL_USER,
|
|
password: process.env.MYSQL_PASSWORD,
|
|
database: process.env.MYSQL_DATABASE
|
|
})
|
|
|
|
// Connect to the database
|
|
connection.connect(error => {
|
|
if (error) return console.error(error)
|
|
console.log(`Connected to MySql database as id ${connection.threadId} !`)
|
|
})
|
|
|
|
// Check if the user already exists in the rewards table
|
|
connection.query('SELECT * FROM rewards WHERE user_id = ?', [user_id], (error, results) => {
|
|
if (error) return console.error(error)
|
|
|
|
if (results.length === 0) {
|
|
// User doesn't exist, insert a new row
|
|
connection.query('INSERT INTO rewards SET ?', { user_id, user_name, count: 1 }, error => {
|
|
if (error) return console.error(error)
|
|
})
|
|
} else {
|
|
// User exists, update the count
|
|
const newRow = { count: results[0].count + 1 }
|
|
connection.query('UPDATE rewards SET ? WHERE user_id = ?', [newRow, user_id], error => {
|
|
if (error) return console.error(error)
|
|
})
|
|
}
|
|
})
|
|
|
|
// Terminate the connection to the database
|
|
connection.end()
|
|
} |