Add user data caching

This commit is contained in:
2022-06-06 20:11:07 +07:00
parent aa268b584d
commit 22f711dc80
5 changed files with 98 additions and 25 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ import { sendHybridInteractionMessageResponse, makeInfoEmbed } from '../utils/Di
const EMBEDS = { const EMBEDS = {
INFO: async (data: Message | Interaction) => { INFO: async (data: Message | Interaction) => {
let GuildCache = await Cache.getGuild(data.guildId!); let GuildCache = await Cache.getCachedGuild(data.guildId!);
// TODO: Better error handling // TODO: Better error handling
if (typeof GuildCache === 'undefined') throw new Error('Guild not found'); if (typeof GuildCache === 'undefined') throw new Error('Guild not found');
+2 -2
View File
@@ -60,7 +60,7 @@ const EMBEDS = {
}); });
}, },
NO_SERVICE_ANNOUNCEMENT_STATUS_PROVIDED: async (data: Message | Interaction) => { NO_SERVICE_ANNOUNCEMENT_STATUS_PROVIDED: async (data: Message | Interaction) => {
let GuildCache = await Cache.getGuild(data.guild!.id); let GuildCache = await Cache.getCachedGuild(data.guild!.id);
// TODO: Better error handling // TODO: Better error handling
if (typeof GuildCache === 'undefined') throw new Error('Guild not found'); if (typeof GuildCache === 'undefined') throw new Error('Guild not found');
@@ -288,7 +288,7 @@ export default class Settings extends DiscordModule {
}); });
await Cache.updateGuildCache(data.getGuild()!.id); await Cache.updateGuildCache(data.getGuild()!.id);
let GuildCache = await Cache.getGuild(data.getGuild()!.id); let GuildCache = await Cache.getCachedGuild(data.getGuild()!.id);
const newStatusBool = ['true', 'yes', 'y', 'enable'].includes( const newStatusBool = ['true', 'yes', 'y', 'enable'].includes(
newStatus.toLowerCase() newStatus.toLowerCase()
+21 -1
View File
@@ -1,3 +1,4 @@
import { User as PrismaUser } from '@prisma/client';
import { import {
Message, Message,
Interaction, Interaction,
@@ -16,6 +17,7 @@ import {
import DiscordMusicPlayer from '../../providers/DiscordMusicPlayer'; import DiscordMusicPlayer from '../../providers/DiscordMusicPlayer';
import Users from '../../services/Users'; import Users from '../../services/Users';
import Cache from '../../providers/Cache';
const EMBEDS = { const EMBEDS = {
DEBUG_INFO: (data: Message | Interaction) => { DEBUG_INFO: (data: Message | Interaction) => {
@@ -25,7 +27,7 @@ const EMBEDS = {
fields: [ fields: [
{ {
name: 'Available arguments', name: 'Available arguments',
value: '``invalidInteraction`` ``crashMusicPlayer`` ``crash`` ``activemusicplayer``' value: '``invalidInteraction`` ``crashMusicPlayer`` ``crash`` ``activemusicplayer`` ``mydata``'
} }
], ],
user: data instanceof Interaction ? data.user : data.author user: data instanceof Interaction ? data.user : data.author
@@ -53,6 +55,14 @@ const EMBEDS = {
user: data instanceof Interaction ? data.user : data.author user: data instanceof Interaction ? data.user : data.author
}); });
}, },
YOUR_USER_DATA: (data: Message | Interaction, userData?: PrismaUser) => {
return makeInfoEmbed({
icon: '📃',
title: `Your user data`,
description: JSON.stringify(userData),
user: data instanceof Interaction ? data.user : data.author
});
},
NOT_DEVELOPER: (data: Message | Interaction) => { NOT_DEVELOPER: (data: Message | Interaction) => {
return makeErrorEmbed({ return makeErrorEmbed({
title: 'Developer only', title: 'Developer only',
@@ -127,6 +137,14 @@ export default class Debug extends DiscordModule {
] ]
}); });
}, },
myData: async (data: HybridInteractionMessage) => {
const userData = await Cache.getCachedUser(user.id);
await sendHybridInteractionMessageResponse(data, {
embeds: [
EMBEDS.YOUR_USER_DATA(data.getRaw(), userData)
]
});
},
invalidInteraction: async (data: HybridInteractionMessage) => { invalidInteraction: async (data: HybridInteractionMessage) => {
const row = new MessageActionRow().addComponents( const row = new MessageActionRow().addComponents(
new MessageButton() new MessageButton()
@@ -170,6 +188,8 @@ export default class Debug extends DiscordModule {
return await funct.crashMusicPlayer(data); return await funct.crashMusicPlayer(data);
case 'activemusicplayer': case 'activemusicplayer':
return await funct.activeMusicPlayer(data); return await funct.activeMusicPlayer(data);
case 'mydata':
return await funct.myData(data);
} }
} }
} }
+62 -14
View File
@@ -1,38 +1,51 @@
import { Guild } from '@prisma/client'; import { User, Guild } from '@prisma/client';
import { Snowflake } from 'discord-api-types/v10'; import { Snowflake } from 'discord-api-types/v10';
import Prisma from './Prisma'; import Prisma from './Prisma';
class Cache { class Cache {
private cache: any; private cache: {
Guilds: { [key: Snowflake]: Guild };
Users: { [key: Snowflake]: User };
};
constructor() { constructor() {
this.cache = { this.cache = {
Guilds: {} Guilds: {},
Users: {}
}; };
} }
public async updateGuildsCache() { public async updateGuildsCache() {
const Guilds = await Prisma.client.guild.findMany(); const Guilds = await Prisma.client.guild.findMany();
for (let Guild of Guilds) { for (let guild of Guilds) {
this.setGuildData(Guild.id, Guild); this.setGuildCache(guild.id, guild);
} }
} }
public async updateGuildCache(guildID: Snowflake) { public async updateGuildCache(id: Snowflake) {
const DBGuild = await Prisma.client.guild.findFirst({ where: { id: guildID } }); const DBGuild = await Prisma.client.guild.findFirst({ where: { id: id } });
// TODO: Try to fetch guild, create if not found or throw error
if (DBGuild === null) return; if (DBGuild === null) return;
this.setGuildData(guildID, DBGuild); this.setGuildCache(id, DBGuild);
} }
public setGuildData(id: string, data: Object): void { public async updateUserCache(id: Snowflake) {
this.cache.Guilds[id] = data; let user = await Prisma.client.user.findUnique({ where: { id } });
if (!user) {
user = await Prisma.client.user.create({
data: {
id
}
});
}
this.setUserCache(user.id, user);
} }
public async getGuild(id: string): Promise<Guild | undefined> { public async getCachedGuild(id: Snowflake): Promise<Guild | undefined> {
if (typeof this.cache.Guilds[id] !== 'undefined') return this.cache.Guilds[id]; if (typeof this.cache.Guilds[id] !== 'undefined') return this.cache.Guilds[id];
const Guild = await Prisma.client.guild.findFirst({ const Guild = await Prisma.client.guild.findUnique({
where: { where: {
id: id id: id
} }
@@ -40,13 +53,48 @@ class Cache {
if (Guild === null) return undefined; if (Guild === null) return undefined;
this.setGuildData(Guild.id, Guild); this.setGuildCache(Guild.id, Guild);
return this.cache.Guilds[id]; return this.cache.Guilds[id];
} }
public getGuilds(): void { public async getCachedUser(id: Snowflake): Promise<User | undefined> {
if (typeof this.cache.Users[id] !== 'undefined') return this.cache.Users[id];
const user = await Prisma.client.user.findUnique({
where: {
id: id
}
});
if (user === null) return undefined;
this.setUserCache(user.id, user);
return this.cache.Users[id];
}
public setGuildCache(id: Snowflake, data: Guild): void {
this.cache.Guilds[id] = data;
}
public setUserCache(id: Snowflake, data: User): void {
this.cache.Users[id] = data;
}
public isGuildCached(id: Snowflake) {
return typeof this.cache.Guilds[id] !== 'undefined';
}
public isUserCached(id: Snowflake) {
return typeof this.cache.Users[id] !== 'undefined';
}
public getCachedGuilds(): Object {
return this.cache.Guilds; return this.cache.Guilds;
} }
public getCachedUsers(): Object {
return this.cache.Users;
}
} }
export default new Cache(); export default new Cache();
+12 -7
View File
@@ -124,7 +124,11 @@ class Discord {
}); });
// Interaction create event to modules // Interaction create event to modules
this.client.on('interactionCreate', (interaction: Interaction) => { this.client.on('interactionCreate', async (interaction: Interaction) => {
if(!Cache.isUserCached(interaction.user.id))
await Cache.updateUserCache(interaction.user.id);
for (const module of this.loaded_module) { for (const module of this.loaded_module) {
let thisModule: DiscordModule = module[1]; let thisModule: DiscordModule = module[1];
@@ -175,7 +179,7 @@ class Discord {
if (message.author.bot) return; if (message.author.bot) return;
if (typeof message.guild?.id === 'undefined') return; if (typeof message.guild?.id === 'undefined') return;
let GuildCache = await Cache.getGuild(message.guild.id); let GuildCache = await Cache.getCachedGuild(message.guild.id);
if (typeof GuildCache === 'undefined' || typeof GuildCache.prefix === 'undefined') if (typeof GuildCache === 'undefined' || typeof GuildCache.prefix === 'undefined')
return; return;
@@ -243,15 +247,10 @@ class Discord {
} else { } else {
if (noPrefixMessage.charAt(0) !== ' ') return; if (noPrefixMessage.charAt(0) !== ' ') return;
} }
//if(noPrefixMessage.charAt(0) !== ' ' && !symbols.includes(noPrefixMessage.charAt(0))) return;
} }
if (noPrefixMessage === '') return; if (noPrefixMessage === '') return;
if (noPrefixMessage.charAt(0) === ' ') { if (noPrefixMessage.charAt(0) === ' ') {
/*if(symbols.includes(GuildCache.prefix.charAt(GuildCache.prefix.length - 1))) {
if((GuildCache.prefix.indexOf(' ') >= 0)) return;
}*/
noPrefixMessage = noPrefixMessage.substring(1); noPrefixMessage = noPrefixMessage.substring(1);
} }
@@ -264,6 +263,9 @@ class Discord {
if (args.length === 0) args = []; if (args.length === 0) args = [];
if(!Cache.isUserCached(message.author.id))
await Cache.updateUserCache(message.author.id);
for (const module of this.loaded_module) { for (const module of this.loaded_module) {
let thisModule: DiscordModule = module[1]; let thisModule: DiscordModule = module[1];
thisModule.GuildOnCommand(command, args, message); thisModule.GuildOnCommand(command, args, message);
@@ -294,6 +296,9 @@ class Discord {
if (args.length === 0) args = []; if (args.length === 0) args = [];
if(!Cache.isUserCached(message.author.id))
await Cache.updateUserCache(message.author.id);
for (const module of this.loaded_module) { for (const module of this.loaded_module) {
let thisModule: DiscordModule = module[1]; let thisModule: DiscordModule = module[1];
thisModule.GuildOnCommand(command, args, message); thisModule.GuildOnCommand(command, args, message);