58 lines
2.1 KiB
JavaScript
58 lines
2.1 KiB
JavaScript
const mysql = require('mysql2/promise')
|
|
const axios = require('axios')
|
|
require('dotenv').config()
|
|
|
|
module.exports = rewardRedemption = (async (viewer_id, viewer_name, client_id, access_token, id, broadcaster_id, reward_id) => {
|
|
// Create a connection to the MySQL database
|
|
const connection = await mysql.createConnection({
|
|
host: process.env.MYSQL_HOST,
|
|
port: process.env.MYSQL_PORT,
|
|
user: process.env.MYSQL_USER,
|
|
password: process.env.MYSQL_PASSWORD,
|
|
database: process.env.MYSQL_DATABASE
|
|
})
|
|
|
|
const result = {}
|
|
|
|
// Check if the viewer already exists in the rewards table
|
|
await connection.query('SELECT * FROM rewards WHERE viewer_id = ?', [viewer_id])
|
|
.then(async ([rows, fields]) => {
|
|
if (rows.length === 0) {
|
|
// Viewer doesn't exist, insert a new row
|
|
let sql_data = { viewer_id, viewer_name, count: 1, current_count: 1 }
|
|
|
|
await connection.query('INSERT INTO rewards SET ?', sql_data).catch(error => { console.error(error) })
|
|
return result.status = 'insert_entry'
|
|
}
|
|
else {
|
|
// Viewer exists, update the count
|
|
result.count = rows[0].count + 1
|
|
result.current_count = rows[0].current_count + 1
|
|
let sql_data = { count: result.count, current_count: result.current_count }
|
|
|
|
await connection.query('UPDATE rewards SET ? WHERE viewer_id = ?', [sql_data, viewer_id]).catch(error => { console.error(error) })
|
|
return result.status = 'update_entry'
|
|
}
|
|
}).catch(error => { console.error(error) })
|
|
|
|
// Terminate the connection to the database
|
|
await connection.end()
|
|
|
|
// Fullfil the reward redemption
|
|
if (result.status === 'insert_entry' || result.status === 'update_entry') {
|
|
await axios.patch(`https://api.twitch.tv/helix/channel_points/custom_rewards/redemptions?id=${id}&broadcaster_id=${broadcaster_id}&reward_id=${reward_id}`, {
|
|
status: 'FULFILLED'
|
|
}, {
|
|
headers: {
|
|
'Authorization': `Bearer ${access_token}`,
|
|
'Client-Id': client_id,
|
|
'Content-Type': 'application/json'
|
|
}
|
|
}).then(response => {
|
|
console.log(response.data)
|
|
//return response.data.data[0].status
|
|
}).catch(error => { console.log(error.response.data) })
|
|
}
|
|
|
|
return result
|
|
}) |