Merge pull request #74 from veganhacktivists/database_refactor

perf(arabot): change database connection to global instance
This commit is contained in:
Anthony Berg 2023-02-07 22:49:36 +00:00 committed by GitHub
commit 6e4607161b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 38 additions and 147 deletions

View File

@ -21,10 +21,11 @@
*/ */
import { GatewayIntentBits } from 'discord.js'; import { GatewayIntentBits } from 'discord.js';
import { LogLevel, SapphireClient } from '@sapphire/framework'; import { LogLevel, SapphireClient, container } from '@sapphire/framework';
import { ScheduledTaskRedisStrategy } from '@sapphire/plugin-scheduled-tasks/register-redis'; import { ScheduledTaskRedisStrategy } from '@sapphire/plugin-scheduled-tasks/register-redis';
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import '@sapphire/plugin-logger/register'; import '@sapphire/plugin-logger/register';
import { PrismaClient } from '@prisma/client';
require('dotenv').config(); require('dotenv').config();
@ -64,13 +65,21 @@ const main = async () => {
try { try {
const token = process.env.DISCORD_TOKEN; const token = process.env.DISCORD_TOKEN;
client.logger.info('Logging in'); client.logger.info('Logging in');
container.database = await new PrismaClient();
await client.login(token); await client.login(token);
client.logger.info('Logged in'); client.logger.info('Logged in');
} catch (error) { } catch (error) {
client.logger.fatal(error); client.logger.fatal(error);
await container.database.$disconnect();
client.destroy(); client.destroy();
process.exit(1); process.exit(1);
} }
}; };
declare module '@sapphire/pieces' {
interface Container {
database: PrismaClient;
}
}
main(); main();

View File

@ -1,11 +1,8 @@
import { PrismaClient } from '@prisma/client'; import { container } from '@sapphire/framework';
export async function addBan(userId: string, modId: string, reason: string) { export async function addBan(userId: string, modId: string, reason: string) {
// Initialise the database connection
const prisma = new PrismaClient();
// Add the user to the database // Add the user to the database
await prisma.ban.create({ await container.database.ban.create({
data: { data: {
user: { user: {
connect: { connect: {
@ -20,16 +17,10 @@ export async function addBan(userId: string, modId: string, reason: string) {
reason, reason,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
export async function removeBan(userId: string, modId: string) { export async function removeBan(userId: string, modId: string) {
// Initialise the database connection const ban = await container.database.ban.findFirst({
const prisma = new PrismaClient();
const ban = await prisma.ban.findFirst({
where: { where: {
userId, userId,
}, },
@ -43,7 +34,7 @@ export async function removeBan(userId: string, modId: string) {
} }
// Query to deactivate the specific sus note // Query to deactivate the specific sus note
await prisma.ban.update({ await container.database.ban.update({
where: { where: {
id: ban.id, id: ban.id,
}, },
@ -53,16 +44,10 @@ export async function removeBan(userId: string, modId: string) {
active: false, active: false,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
export async function checkActive(userId: string) { export async function checkActive(userId: string) {
// Initialise the database connection const ban = await container.database.ban.findFirst({
const prisma = new PrismaClient();
const ban = await prisma.ban.findFirst({
where: { where: {
userId, userId,
}, },
@ -79,10 +64,7 @@ export async function checkActive(userId: string) {
} }
export async function getReason(userId: string) { export async function getReason(userId: string) {
// Initialise the database connection const ban = await container.database.ban.findFirst({
const prisma = new PrismaClient();
const ban = await prisma.ban.findFirst({
where: { where: {
userId, userId,
}, },

View File

@ -18,24 +18,18 @@
*/ */
import type { GuildMember, GuildMemberRoleManager } from 'discord.js'; import type { GuildMember, GuildMemberRoleManager } from 'discord.js';
import { PrismaClient } from '@prisma/client'; import { container } from '@sapphire/framework';
import IDs from '#utils/ids'; import IDs from '#utils/ids';
// Checks if the user exists on the database // Checks if the user exists on the database
export async function userExists(userId: string) { export async function userExists(userId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Counts if the user is on the database by their snowflake // Counts if the user is on the database by their snowflake
const userQuery = await prisma.user.count({ const userQuery = await container.database.user.count({
where: { where: {
id: userId, id: userId,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
// If the user is found on the database, then return true, otherwise, false. // If the user is found on the database, then return true, otherwise, false.
return userQuery > 0; return userQuery > 0;
} }
@ -58,11 +52,8 @@ function getRoles(roles: GuildMemberRoleManager) {
// Adds the user to the database if they were already on the server before the bot/database // Adds the user to the database if they were already on the server before the bot/database
export async function addExistingUser(user: GuildMember) { export async function addExistingUser(user: GuildMember) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Counts if the user is on the database by their snowflake // Counts if the user is on the database by their snowflake
const userQuery = await prisma.user.count({ const userQuery = await container.database.user.count({
where: { where: {
id: user.id, id: user.id,
}, },
@ -77,7 +68,7 @@ export async function addExistingUser(user: GuildMember) {
const roles = getRoles(user.roles); const roles = getRoles(user.roles);
// Create the user in the database // Create the user in the database
await prisma.user.create({ await container.database.user.create({
data: { data: {
id: user.id, id: user.id,
vegan: roles.vegan, vegan: roles.vegan,
@ -90,18 +81,12 @@ export async function addExistingUser(user: GuildMember) {
muted: roles.muted, muted: roles.muted,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
// Add an empty user to database in case they are not on the server // Add an empty user to database in case they are not on the server
export async function addEmptyUser(userId: string) { export async function addEmptyUser(userId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Counts if the user is on the database by their snowflake // Counts if the user is on the database by their snowflake
const userQuery = await prisma.user.count({ const userQuery = await container.database.user.count({
where: { where: {
id: userId, id: userId,
}, },
@ -113,14 +98,11 @@ export async function addEmptyUser(userId: string) {
} }
// Create the user in the database // Create the user in the database
await prisma.user.create({ await container.database.user.create({
data: { data: {
id: userId, id: userId,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
export async function updateUser(user: GuildMember) { export async function updateUser(user: GuildMember) {
@ -133,10 +115,7 @@ export async function updateUser(user: GuildMember) {
// Parse all the roles into a dictionary // Parse all the roles into a dictionary
const roles = getRoles(user.roles); const roles = getRoles(user.roles);
// Initialises Prisma Client await container.database.user.update({
const prisma = new PrismaClient();
await prisma.user.update({
where: { where: {
id: user.id, id: user.id,
}, },
@ -152,17 +131,11 @@ export async function updateUser(user: GuildMember) {
muted: roles.muted, muted: roles.muted,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
export async function fetchRoles(user: string) { export async function fetchRoles(user: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Get the user's roles // Get the user's roles
const roleQuery = await prisma.user.findUnique({ const roleQuery = await container.database.user.findUnique({
where: { where: {
id: user, id: user,
}, },
@ -177,9 +150,6 @@ export async function fetchRoles(user: string) {
}, },
}); });
// Close the database connection
await prisma.$disconnect();
// Assign roles to role snowflakes // Assign roles to role snowflakes
const roles = []; const roles = [];

View File

@ -1,11 +1,8 @@
import { PrismaClient } from '@prisma/client'; import { container } from '@sapphire/framework';
export async function addToDatabase(userId: string, modId: string, message: string) { export async function addToDatabase(userId: string, modId: string, message: string) {
// Initialise the database connection
const prisma = new PrismaClient();
// Add the user to the database // Add the user to the database
await prisma.sus.create({ await container.database.sus.create({
data: { data: {
user: { user: {
connect: { connect: {
@ -20,52 +17,36 @@ export async function addToDatabase(userId: string, modId: string, message: stri
note: message, note: message,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
// Get a list of sus notes from the user // Get a list of sus notes from the user
export async function findNotes(userId: string, active: boolean) { export async function findNotes(userId: string, active: boolean) {
// Initialise the database connection
const prisma = new PrismaClient();
// Query to get the specific user's sus notes // Query to get the specific user's sus notes
const note = await prisma.sus.findMany({ const note = await container.database.sus.findMany({
where: { where: {
userId, userId,
active, active,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
return note; return note;
} }
// Get one note from the id // Get one note from the id
export async function getNote(noteId: number) { export async function getNote(noteId: number) {
// Initialise the database connection
const prisma = new PrismaClient();
// Query to get the specific user's sus notes // Query to get the specific user's sus notes
const note = await prisma.sus.findUnique({ const note = await container.database.sus.findUnique({
where: { where: {
id: noteId, id: noteId,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
return note; return note;
} }
export async function deactivateNote(noteId: number) { export async function deactivateNote(noteId: number) {
// Initialise the database connection
const prisma = new PrismaClient();
// Query to deactivate the specific sus note // Query to deactivate the specific sus note
await prisma.sus.update({ await container.database.sus.update({
where: { where: {
id: noteId, id: noteId,
}, },
@ -73,17 +54,11 @@ export async function deactivateNote(noteId: number) {
active: false, active: false,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }
export async function deactivateAllNotes(userId: string) { export async function deactivateAllNotes(userId: string) {
// Initialise the database connection
const prisma = new PrismaClient();
// Query to deactivate the specific user's sus notes // Query to deactivate the specific user's sus notes
await prisma.sus.updateMany({ await container.database.sus.updateMany({
where: { where: {
userId: { userId: {
contains: userId, contains: userId,
@ -93,7 +68,4 @@ export async function deactivateAllNotes(userId: string) {
active: false, active: false,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
} }

View File

@ -18,7 +18,7 @@
*/ */
import type { GuildMember } from 'discord.js'; import type { GuildMember } from 'discord.js';
import { PrismaClient } from '@prisma/client'; import { container } from '@sapphire/framework';
import { updateUser } from '#utils/database/dbExistingUser'; import { updateUser } from '#utils/database/dbExistingUser';
import { leaveBan } from '#utils/verificationConfig'; import { leaveBan } from '#utils/verificationConfig';
import { fibonacci } from '#utils/mathsSeries'; import { fibonacci } from '#utils/mathsSeries';
@ -27,10 +27,7 @@ export async function joinVerification(channelId: string, user: GuildMember) {
// Update the user on the database with the current roles they have // Update the user on the database with the current roles they have
await updateUser(user); await updateUser(user);
// Initialises Prisma Client await container.database.verify.create({
const prisma = new PrismaClient();
await prisma.verify.create({
data: { data: {
id: channelId, id: channelId,
user: { user: {
@ -40,16 +37,10 @@ export async function joinVerification(channelId: string, user: GuildMember) {
}, },
}, },
}); });
// Close database connection
await prisma.$disconnect();
} }
export async function startVerification(channelId: string) { export async function startVerification(channelId: string) {
// Initialises Prisma Client await container.database.verify.update({
const prisma = new PrismaClient();
await prisma.verify.update({
where: { where: {
id: channelId, id: channelId,
}, },
@ -57,17 +48,11 @@ export async function startVerification(channelId: string) {
startTime: new Date(), startTime: new Date(),
}, },
}); });
// Close database connection
await prisma.$disconnect();
} }
export async function getUser(channelId: string) { export async function getUser(channelId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Get the snowflake of the user verifying // Get the snowflake of the user verifying
const user = await prisma.verify.findUnique({ const user = await container.database.verify.findUnique({
where: { where: {
id: channelId, id: channelId,
}, },
@ -76,9 +61,6 @@ export async function getUser(channelId: string) {
}, },
}); });
// Close database connection
await prisma.$disconnect();
// Check the user could be found // Check the user could be found
if (user === null) { if (user === null) {
return null; return null;
@ -109,11 +91,8 @@ export async function finishVerification(
convinced: boolean convinced: boolean
} }, } },
) { ) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// TODO potentially add an incomplete tracker? // TODO potentially add an incomplete tracker?
await prisma.verify.update({ await container.database.verify.update({
where: { where: {
id: channelId, id: channelId,
}, },
@ -139,18 +118,12 @@ export async function finishVerification(
food: info.food, food: info.food,
}, },
}); });
// Close database connection
await prisma.$disconnect();
} }
// Checks if verification was complete // Checks if verification was complete
export async function checkFinish(channelId: string) { export async function checkFinish(channelId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Get the snowflake of the user verifying // Get the snowflake of the user verifying
const finish = await prisma.verify.findUnique({ const finish = await container.database.verify.findUnique({
where: { where: {
id: channelId, id: channelId,
}, },
@ -159,9 +132,6 @@ export async function checkFinish(channelId: string) {
}, },
}); });
// Close database connection
await prisma.$disconnect();
// Checks if query returned is null // Checks if query returned is null
if (finish === null) { if (finish === null) {
return false; return false;
@ -173,30 +143,21 @@ export async function checkFinish(channelId: string) {
// Counts how many times the user has not had a verifier join their VC before leaving // Counts how many times the user has not had a verifier join their VC before leaving
export async function countIncomplete(userId: string) { export async function countIncomplete(userId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Count how many times the user has not completed a verification // Count how many times the user has not completed a verification
const incompleteCount = await prisma.verify.count({ const incompleteCount = await container.database.verify.count({
where: { where: {
userId, userId,
finishTime: null, finishTime: null,
}, },
}); });
// Close the database connection
await prisma.$disconnect();
return incompleteCount; return incompleteCount;
} }
// Gets the amount of time left on the block // Gets the amount of time left on the block
export async function blockTime(userId: string) { export async function blockTime(userId: string) {
// Initialises Prisma Client
const prisma = new PrismaClient();
// Count how many times the user has not completed a verification // Count how many times the user has not completed a verification
const verification = await prisma.verify.findFirst({ const verification = await container.database.verify.findFirst({
where: { where: {
userId, userId,
}, },
@ -205,9 +166,6 @@ export async function blockTime(userId: string) {
}, },
}); });
// Close the database connection
await prisma.$disconnect();
if (verification === null) { if (verification === null) {
return 0; return 0;
} }