improve caching

This commit is contained in:
Skillz
2020-05-21 11:26:21 -04:00
parent 2bb650368f
commit 7bb0c428bf
2 changed files with 27 additions and 11 deletions

View File

@@ -328,9 +328,12 @@ function handleDiscordPayload(data: DiscordPayload) {
if (channel) channel.last_message_id = options.id;
const message = createMessage(options);
// Cache the message
cache.messages.set(options.id, message);
if (options.member && options.guild_id) {
const guild = cache.guilds.get(options.guild_id);
const guild = options.guild_id ? cache.guilds.get(options.guild_id) : undefined;
if (options.member) {
// If in a guild cache the author as a member
guild?.members.set(
options.author.id,
createMember(
@@ -339,8 +342,18 @@ function handleDiscordPayload(data: DiscordPayload) {
),
);
}
// Cache the message author themself
cache.users.set(message.author.id, message.author);
options.mentions.forEach((mention) => {
// For each mention cache the user
cache.users.set(mention.id, createUser(mention));
// Cache the member if its a valid member
if (mention.member) {
guild?.members.set(mention.id, createMember({ ...mention.member, user: mention }, guild))
}
});
return eventHandlers.messageCreate?.(message);
}

View File

@@ -11,7 +11,7 @@ import { botID } from "../module/client.ts";
import { cache } from "../utils/cache.ts";
export function createMessage(data: MessageCreateOptions) {
return {
const message = {
...data,
raw: data,
channelID: data.channel_id,
@@ -19,11 +19,11 @@ export function createMessage(data: MessageCreateOptions) {
mentionsEveryone: data.mentions_everyone,
mentionRoles: data.mention_roles,
mentionChannels: data.mention_channels,
mentions: data.mentions.map((user) => createUser(user)),
mentions: data.mentions.map((user) => cache.users.get(user.id)!),
webhookID: data.webhook_id,
messageReference: data.message_reference,
author: createUser({ ...data.author, avatar: data.author.avatar || "" }),
author: cache.users.get(data.author.id)!,
timestamp: Date.parse(data.timestamp),
editedTimestamp: data.edited_timestamp
? Date.parse(data.edited_timestamp)
@@ -32,13 +32,14 @@ export function createMessage(data: MessageCreateOptions) {
/** Delete a message */
delete: (reason?: string) => {
if (
data.guild_id &&
!botHasPermission(data.guild_id, [Permissions.MANAGE_MESSAGES])
) {
throw new Error(Errors.MISSING_MANAGE_MESSAGES);
}
if (data.author.id !== botID) {
// This needs to check the channels permission not the guild permission
if (
!message.guildID ||
!message.channel.hasPermission(botID, [Permissions.MANAGE_MESSAGES])
) {
throw new Error(Errors.MISSING_MANAGE_MESSAGES);
}
}
return RequestManager.delete(
@@ -158,6 +159,8 @@ export function createMessage(data: MessageCreateOptions) {
return createMessage(result as MessageCreateOptions);
},
};
return message;
}
export interface Message extends ReturnType<typeof createMessage> {}