Raccoon-Influencer-Search/libs/db.js
2024-07-11 20:43:47 +02:00

66 lines
1.9 KiB
JavaScript

// Mostly functions for reading/writing in database
const models = require("../models");
const Game = models.Game;
const Channel = models.Channel;
/**
* Checks if a game exists in Game table and returns it
* @param {string} gameName
*/
async function getGame(gameName) {
await Game.sync();
const game = await Game.findOne({ where: { name: gameName } });
return game !== null ? game : false
}
/**
* Checks if a game exists in Channels Table.
* @param {string} gameName
*/
async function getChannels(gameId) {
await Channel.sync();
const channels = await Channel.findAll({ where: { game: gameId } });
return channels.length > 0 ? channels : false
}
async function createGame(gameName, channels) {
const game = Game.create({
name: gameName,
createdAt: Date.now(),
updatedAt: Date.now(),
channels: JSON.stringify(channels),
});
console.log("🔎 Recorded " + gameName + " with " + channels.length + " in the database.")
return game
}
async function createChannel(gameId, channelId, videos, medianViews) {
console.log("🔎 Channel " + channelId + " does not exists in channels table. Creating entry.")
console.log(typeof videos)
const channel = Channel.create({
name: videos[0].snippet.channelTitle,
channelId: channelId,
createdAt: Date.now(),
updatedAt: Date.now(),
game: gameId,
videos: JSON.stringify(videos),
videosCount: videos.length,
medianViews: medianViews,
});
return channel
}
async function updateChannel(channelInDb, videos, medianViews) {
console.log("🔎 Updating Channel")
channelInDb.videosCount = videos.length
channelInDb.medianViews = medianViews
channelInDb.videos = JSON.stringify(videos)
channelInDb.updatedAt = Date.now()
const channel = await channelInDb.save({ fields: ['videosCount', 'medianViews', 'videos', 'updatedAt'] });
return channel
}
module.exports = { getGame, getChannels, createGame, createChannel, updateChannel };