refactoring

This commit is contained in:
Axel Olausson Holtenäs 2023-01-26 13:09:22 +01:00
parent cc8a3b9b3c
commit aea3dfd365
18 changed files with 135 additions and 108 deletions

View file

@ -1,35 +0,0 @@
import { EmbedBuilder, Guild } from "discord.js";
import getEmbedData from "../getEmbedData";
// Construct a base embed for success messages
export const success = async (guild: Guild | null, title: string) => {
const { successColor, footerText, footerIcon } = await getEmbedData(guild);
return new EmbedBuilder()
.setTimestamp(new Date())
.setTitle(title)
.setColor(successColor)
.setFooter({ text: footerText, iconURL: footerIcon });
};
// Construct a base embed for wait messages
export const wait = async (guild: Guild | null, title: string) => {
const { waitColor, footerText, footerIcon } = await getEmbedData(guild);
return new EmbedBuilder()
.setTimestamp(new Date())
.setTitle(title)
.setColor(waitColor)
.setFooter({ text: footerText, iconURL: footerIcon });
};
// Construct a base embed for error messages
export const error = async (guild: Guild | null, title: string) => {
const { errorColor, footerText, footerIcon } = await getEmbedData(guild);
return new EmbedBuilder()
.setTimestamp(new Date())
.setTitle(title)
.setColor(errorColor)
.setFooter({ text: footerText, iconURL: footerIcon });
};

View file

@ -1,3 +0,0 @@
export default (text: string): string => {
return text.charAt(0).toUpperCase() + text.slice(1);
};

View file

@ -5,8 +5,8 @@ export default (
permission: PermissionResolvable
) => {
if (!interaction.memberPermissions)
throw new Error("Could not check user for permissions");
throw new Error("Failed to check your permissions");
if (!interaction.memberPermissions.has(permission))
throw new Error("Permission denied");
throw new Error(`You do not have the required permission: ${permission}`);
};

View file

@ -1,18 +0,0 @@
import { Guild, User } from "discord.js";
export default (guild: Guild, user: User, amount: number) => {
// 1. Verify that the amount is not above 100.000.000 credits.
if (amount > 100000000) {
throw new Error("You can't give more than 1.000.000 credits.");
}
// 2. Verify that the amount is not below 1 credits.
if (amount <= 0) {
throw new Error("You can't give below one credit.");
}
// 3. Verify that the user is not an bot.
if (user.bot) {
throw new Error("You can't give to an bot.");
}
};

25
src/helpers/deferReply.ts Normal file
View file

@ -0,0 +1,25 @@
import { BaseInteraction, EmbedBuilder } from "discord.js";
import getEmbedData from "./getEmbedConfig";
export default async (interaction: BaseInteraction, ephemeral: boolean) => {
if (!interaction.isRepliable())
throw new Error(`Failed to reply to your request`);
await interaction.deferReply({ ephemeral });
const embedConfig = await getEmbedData(interaction.guild);
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setFooter({
text: embedConfig.footerText,
iconURL: embedConfig.footerIcon,
})
.setTimestamp(new Date())
.setTitle("⏳︱Your request are being processed")
.setColor(embedConfig.waitColor)
.setDescription("This might take a while, please wait..."),
],
});
};

View file

@ -1,5 +1,5 @@
import crypto from "crypto";
import { IEncryptionData } from "../../interfaces/EncryptionData";
import { IEncryptionData } from "../interfaces/EncryptionData";
const iv = crypto.randomBytes(16);

View file

@ -1,6 +1,6 @@
import { ColorResolvable, Guild } from "discord.js";
import prisma from "../../handlers/database";
import logger from "../../middlewares/logger";
import prisma from "../handlers/prisma";
import logger from "../middlewares/logger";
export default async (guild?: Guild | null) => {
const {

View file

@ -1,7 +0,0 @@
import logger from "../../middlewares/logger";
export default (count: number, noun: string, suffix?: string): string => {
const result = `${count} ${noun}${count !== 1 ? suffix || "s" : ""}`;
logger?.silly(`Pluralized ${count} to ${result}`);
return result;
};

View file

@ -1,5 +1,5 @@
import fs from "fs";
import logger from "../../middlewares/logger";
import logger from "../middlewares/logger";
const fsPromises = fs.promises;
export default async (path: string) => {

View file

@ -1,7 +1,7 @@
import { ChannelType, EmbedBuilder, Guild } from "discord.js";
import prisma from "../../handlers/database";
import getEmbedConfig from "../../helpers/getEmbedData";
import logger from "../../middlewares/logger";
import prisma from "../handlers/prisma";
import logger from "../middlewares/logger";
import getEmbedConfig from "./getEmbedConfig";
export default async (guild: Guild, embed: EmbedBuilder) => {
const getGuildConfigAudits = await prisma.guildConfigAudits.findUnique({

View file

@ -0,0 +1,34 @@
// Dependencies
import { ActivitiesOptions, ActivityType, Client } from "discord.js";
import logger from "../middlewares/logger";
// Function
export default (client: Client) => {
// 1. Destructure the client.
const { guilds, user } = client;
if (!user) throw new Error("No user found");
// 2. Get the total number of guilds and members.
const memberCount = guilds.cache.reduce((a, g) => a + g.memberCount, 0);
const guildCount = guilds.cache.size;
const activities: ActivitiesOptions[] = [
{
name: `${guildCount} servers︱${memberCount} users`,
type: ActivityType.Watching,
},
];
const activity = activities[Math.floor(Math.random() * activities.length)];
// 3. Set the presence.
user.setActivity(activity);
// 4. Log the presence.
return logger.debug({
guildCount,
memberCount,
message: `Presence updated`,
activity,
});
};

View file

@ -1,5 +1,5 @@
import { Guild, User } from "discord.js";
import db from "../../handlers/database";
import db from "../handlers/prisma";
export default async (guild: Guild, user: User) => {
return await db.guildMember.upsert({

View file

@ -0,0 +1,11 @@
import give from "./transactionTypes/give";
import set from "./transactionTypes/set";
import take from "./transactionTypes/take";
import transfer from "./transactionTypes/transfer";
export default {
give,
set,
take,
transfer,
};

View file

@ -1,12 +1,11 @@
import { Guild, User } from "discord.js";
import prisma from "../../handlers/database";
import logger from "../../middlewares/logger";
import transactionRules from "./transactionRules";
import prisma from "../../../handlers/prisma";
import validateTransaction from "../validateTransaction";
export default async (guild: Guild, user: User, amount: number) => {
return await prisma.$transaction(async (tx) => {
// 1. Check if the transaction is valid.
transactionRules(guild, user, amount);
validateTransaction(guild, user, amount);
// 2. Make the transaction.
const recipient = await tx.guildMemberCredit.upsert({

View file

@ -1,11 +1,11 @@
import { Guild, User } from "discord.js";
import prisma from "../../handlers/database";
import transactionRules from "./transactionRules";
import prisma from "../../../handlers/prisma";
import validateTransaction from "../validateTransaction";
export default async (guild: Guild, user: User, amount: number) => {
return await prisma.$transaction(async (tx) => {
// 1. Check if the transaction is valid.
transactionRules(guild, user, amount);
validateTransaction(guild, user, amount);
// 2. Make the transaction.
const recipient = await tx.guildMemberCredit.upsert({

View file

@ -1,11 +1,11 @@
import { Guild, User } from "discord.js";
import prisma from "../../handlers/database";
import transactionRules from "./transactionRules";
import prisma from "../../../handlers/prisma";
import validateTransaction from "../validateTransaction";
export default async (guild: Guild, user: User, amount: number) => {
return await prisma.$transaction(async (tx) => {
// 1. Check if the transaction is valid.
transactionRules(guild, user, amount);
validateTransaction(guild, user, amount);
// 2. Make the transaction.
const recipient = await tx.guildMemberCredit.upsert({

View file

@ -1,11 +1,15 @@
import { Guild, User } from "discord.js";
import prisma from "../../handlers/database";
import transactionRules from "./transactionRules";
import prisma from "../../../handlers/prisma";
import validateTransaction from "../validateTransaction";
export default async (guild: Guild, from: User, to: User, amount: number) => {
export default async (
guild: Guild,
fromUser: User,
toUser: User,
amount: number
) => {
return await prisma.$transaction(async (tx) => {
// 1. Decrement amount from the sender.
const sender = await tx.guildMemberCredit.upsert({
const fromTransaction = await tx.guildMemberCredit.upsert({
update: {
balance: {
decrement: amount,
@ -17,8 +21,8 @@ export default async (guild: Guild, from: User, to: User, amount: number) => {
create: {
user: {
connectOrCreate: {
create: { id: from.id },
where: { id: from.id },
create: { id: fromUser.id },
where: { id: fromUser.id },
},
},
guild: {
@ -28,33 +32,30 @@ export default async (guild: Guild, from: User, to: User, amount: number) => {
},
},
},
where: { userId_guildId: { userId: from.id, guildId: guild.id } },
where: {
userId_guildId: { userId: fromUser.id, guildId: guild.id },
},
},
},
balance: -amount,
},
where: {
userId_guildId: {
userId: from.id,
userId: fromUser.id,
guildId: guild.id,
},
},
});
// 4. Verify that the sender's balance didn't go below zero.
if (sender.balance < 0) {
throw new Error(`${from} doesn't have enough to send ${amount}`);
if (fromTransaction.balance < 0) {
throw new Error(`${fromUser} do not have enough credits`);
}
// 5. Check if the transactions is valid.
transactionRules(guild, from, amount);
transactionRules(guild, to, amount);
if (fromUser.id === toUser.id) {
throw new Error("You can't transfer credits to yourself");
}
// 6. Verify that sender and recipient are not the same user.
if (from.id === to.id) throw new Error("You can't transfer to yourself.");
// 7. Increment the recipient's balance by amount.
const recipient = await tx.guildMemberCredit.upsert({
const toTransaction = await tx.guildMemberCredit.upsert({
update: {
balance: {
increment: amount,
@ -66,8 +67,8 @@ export default async (guild: Guild, from: User, to: User, amount: number) => {
create: {
user: {
connectOrCreate: {
create: { id: to.id },
where: { id: to.id },
create: { id: toUser.id },
where: { id: toUser.id },
},
},
guild: {
@ -77,19 +78,22 @@ export default async (guild: Guild, from: User, to: User, amount: number) => {
},
},
},
where: { userId_guildId: { userId: to.id, guildId: guild.id } },
where: { userId_guildId: { userId: toUser.id, guildId: guild.id } },
},
},
balance: amount,
},
where: {
userId_guildId: {
userId: to.id,
userId: toUser.id,
guildId: guild.id,
},
},
});
return recipient;
validateTransaction(guild, fromUser, amount);
validateTransaction(guild, toUser, amount);
return { fromTransaction, toTransaction };
});
};

View file

@ -0,0 +1,17 @@
import { Guild, User } from "discord.js";
export default (guild: Guild, user: User, amount: number) => {
if (!guild) {
throw new Error("Credits is only available for guilds");
}
// 2. Verify that the amount is not below 1 credits.
if (amount <= 0) {
throw new Error("You can't make an transaction below 1 credits");
}
// 3. Verify that the user is not an bot.
if (user.bot) {
throw new Error("");
}
};