Caching fixes, new Managers, improvemnts

This commit is contained in:
DjDeveloperr 2020-10-31 18:30:33 +05:30
parent 935456906d
commit e8347891d7
10 changed files with 56 additions and 48 deletions

View file

@ -12,7 +12,7 @@ export const channelPinsUpdate: GatewayEventHandler = (
const before = after.refreshFromData({ const before = after.refreshFromData({
last_pin_timestamp: d.last_pin_timestamp last_pin_timestamp: d.last_pin_timestamp
}) })
let raw = gateway.client.channels._get(d.channel_id) as ChannelPayload; const raw = gateway.client.channels._get(d.channel_id) ;
gateway.client.channels.set(after.id, Object.assign(raw, { last_pin_timestamp: d.last_pin_timestamp })) gateway.client.channels.set(after.id, Object.assign(raw, { last_pin_timestamp: d.last_pin_timestamp }))
gateway.client.emit('channelPinsUpdate', before, after) gateway.client.emit('channelPinsUpdate', before, after)
} }

View file

@ -142,7 +142,7 @@ class Gateway {
private async sendIdentify () { private async sendIdentify () {
this.debug("Fetching /gateway/bot...") this.debug("Fetching /gateway/bot...")
let info = await this.client.rest.get(GATEWAY_BOT()) as GatewayBotPayload const info = await this.client.rest.get(GATEWAY_BOT()) as GatewayBotPayload
if(info.session_start_limit.remaining == 0) throw new Error("Session Limit Reached. Retry After " + info.session_start_limit.reset_after + "ms") if(info.session_start_limit.remaining == 0) throw new Error("Session Limit Reached. Retry After " + info.session_start_limit.reset_after + "ms")
this.debug("Recommended Shards: " + info.shards) this.debug("Recommended Shards: " + info.shards)
this.debug("=== Session Limit Info ===") this.debug("=== Session Limit Info ===")

View file

@ -17,7 +17,7 @@ export class BaseManager<T, T2> {
} }
get(key: string): T2 | void { get(key: string): T2 | void {
let raw = this._get(key) const raw = this._get(key)
if(!raw) return if(!raw) return
return new this.dataType(this.client, raw) as any return new this.dataType(this.client, raw) as any
} }

View file

@ -0,0 +1,20 @@
import { Client } from "../models/client.ts";
import { Message } from "../structures/message.ts";
import { MessagePayload } from "../types/channelTypes.ts";
import { CHANNEL_MESSAGE } from "../types/endpoint.ts";
import { BaseManager } from "./BaseManager.ts";
export class MessagesManager extends BaseManager<MessagePayload, Message> {
constructor(client: Client) {
super(client, "messages", Message)
}
fetch(channelID: string, id: string) {
return new Promise((res, rej) => {
this.client.rest.get(CHANNEL_MESSAGE(channelID, id)).then(data => {
this.set(id, data as MessagePayload)
res(new Message(this.client, data as MessagePayload))
}).catch(e => rej(e))
})
}
}

View file

@ -20,7 +20,7 @@ export class DefaultCacheAdapter implements ICacheAdapter {
} }
get(cacheName: string, key: string) { get(cacheName: string, key: string) {
let cache = this.data[cacheName] const cache = this.data[cacheName]
if (!cache) return; if (!cache) return;
return cache.get(key) return cache.get(key)
} }
@ -35,13 +35,13 @@ export class DefaultCacheAdapter implements ICacheAdapter {
} }
delete(cacheName: string, key: string) { delete(cacheName: string, key: string) {
let cache = this.data[cacheName] const cache = this.data[cacheName]
if (!cache) return false if (!cache) return false
return cache.delete(key) return cache.delete(key)
} }
array(cacheName: string) { array(cacheName: string) {
let cache = this.data[cacheName] const cache = this.data[cacheName]
if (!cache) return if (!cache) return
return cache.array() return cache.array()
} }

View file

@ -8,6 +8,7 @@ import { UserManager } from "../managers/UsersManager.ts"
import { GuildManager } from "../managers/GuildsManager.ts" import { GuildManager } from "../managers/GuildsManager.ts"
import { EmojisManager } from "../managers/EmojisManager.ts" import { EmojisManager } from "../managers/EmojisManager.ts"
import { ChannelsManager } from "../managers/ChannelsManager.ts" import { ChannelsManager } from "../managers/ChannelsManager.ts"
import { MessagesManager } from "../managers/MessagesManager.ts"
/** Some Client Options to modify behaviour */ /** Some Client Options to modify behaviour */
export interface ClientOptions { export interface ClientOptions {
@ -27,9 +28,11 @@ export class Client extends EventEmitter {
token?: string token?: string
cache: ICacheAdapter = new DefaultCacheAdapter(this) cache: ICacheAdapter = new DefaultCacheAdapter(this)
intents?: GatewayIntents[] intents?: GatewayIntents[]
users: UserManager = new UserManager(this) users: UserManager = new UserManager(this)
guilds: GuildManager = new GuildManager(this) guilds: GuildManager = new GuildManager(this)
channels: ChannelsManager = new ChannelsManager(this) channels: ChannelsManager = new ChannelsManager(this)
messages: MessagesManager = new MessagesManager(this)
emojis: EmojisManager = new EmojisManager(this) emojis: EmojisManager = new EmojisManager(this)
constructor (options: ClientOptions = {}) { constructor (options: ClientOptions = {}) {

View file

@ -149,7 +149,7 @@ export class RESTManager {
`DiscordBot (discord.deno)`, `DiscordBot (discord.deno)`,
}; };
if(!this.client.token) delete headers["Authorization"]; if(!this.client.token) delete headers.Authorization;
if (method === "get") body = undefined; if (method === "get") body = undefined;
@ -201,7 +201,7 @@ export class RESTManager {
const errorStack = new Error("Location In Your Files:"); const errorStack = new Error("Location In Your Files:");
Error.captureStackTrace(errorStack); Error.captureStackTrace(errorStack);
return new Promise((resolve, reject) => { return await new Promise((resolve, reject) => {
const callback = async () => { const callback = async () => {
try { try {
const rateLimitResetIn = await this.checkRatelimits(url); const rateLimitResetIn = await this.checkRatelimits(url);
@ -349,15 +349,19 @@ export class RESTManager {
get(url: string, body?: unknown) { get(url: string, body?: unknown) {
return this.runMethod("get", url, body); return this.runMethod("get", url, body);
} }
post(url: string, body?: unknown) { post(url: string, body?: unknown) {
return this.runMethod("post", url, body); return this.runMethod("post", url, body);
} }
delete(url: string, body?: unknown) { delete(url: string, body?: unknown) {
return this.runMethod("delete", url, body); return this.runMethod("delete", url, body);
} }
patch(url: string, body?: unknown) { patch(url: string, body?: unknown) {
return this.runMethod("patch", url, body); return this.runMethod("patch", url, body);
} }
put(url: string, body?: unknown) { put(url: string, body?: unknown) {
return this.runMethod("put", url, body); return this.runMethod("put", url, body);
} }

View file

@ -51,14 +51,14 @@ export class Message extends Base {
this.channelID = data.channel_id this.channelID = data.channel_id
this.guildID = data.guild_id this.guildID = data.guild_id
this.author = this.author =
cache.get('user', data.author.id) ?? new User(this.client, data.author) this.client.users.get(data.author.id) || new User(this.client, data.author)
this.content = data.content this.content = data.content
this.timestamp = data.timestamp this.timestamp = data.timestamp
this.editedTimestamp = data.edited_timestamp this.editedTimestamp = data.edited_timestamp
this.tts = data.tts this.tts = data.tts
this.mentionEveryone = data.mention_everyone this.mentionEveryone = data.mention_everyone
this.mentions = data.mentions.map( this.mentions = data.mentions.map(
v => cache.get('user', v.id) ?? new User(client, v) v => this.client.users.get(v.id) || new User(client, v)
) )
this.mentionRoles = data.mention_roles this.mentionRoles = data.mention_roles
this.mentionChannels = data.mention_channels this.mentionChannels = data.mention_channels
@ -73,7 +73,7 @@ export class Message extends Base {
this.application = data.application this.application = data.application
this.messageReference = data.message_reference this.messageReference = data.message_reference
this.flags = data.flags this.flags = data.flags
cache.set('message', this.id, this) this.client.messages.set(this.id, data)
} }
protected readFromData (data: MessagePayload): void { protected readFromData (data: MessagePayload): void {
@ -81,8 +81,8 @@ export class Message extends Base {
this.channelID = data.channel_id ?? this.channelID this.channelID = data.channel_id ?? this.channelID
this.guildID = data.guild_id ?? this.guildID this.guildID = data.guild_id ?? this.guildID
this.author = this.author =
cache.get('user', data.author.id) ?? this.client.users.get(data.author.id) ||
this.author ?? this.author ||
new User(this.client, data.author) new User(this.client, data.author)
this.content = data.content ?? this.content this.content = data.content ?? this.content
this.timestamp = data.timestamp ?? this.timestamp this.timestamp = data.timestamp ?? this.timestamp
@ -91,7 +91,7 @@ export class Message extends Base {
this.mentionEveryone = data.mention_everyone ?? this.mentionEveryone this.mentionEveryone = data.mention_everyone ?? this.mentionEveryone
this.mentions = this.mentions =
data.mentions.map( data.mentions.map(
v => cache.get('user', v.id) ?? new User(this.client, v) v => this.client.users.get(v.id) || new User(this.client, v)
) ?? this.mentions ) ?? this.mentions
this.mentionRoles = data.mention_roles ?? this.mentionRoles this.mentionRoles = data.mention_roles ?? this.mentionRoles
this.mentionChannels = data.mention_channels ?? this.mentionChannels this.mentionChannels = data.mention_channels ?? this.mentionChannels
@ -109,43 +109,24 @@ export class Message extends Base {
} }
// TODO: We have to seperate fetch() // TODO: We have to seperate fetch()
async editMessage (text?: string, option?: MessageOption): Promise<Message> { async edit (text?: string, option?: MessageOption): Promise<Message> {
if (text !== undefined && option !== undefined) { if (text !== undefined && option !== undefined) {
throw new Error('Either text or option is necessary.') throw new Error('Either text or option is necessary.')
} }
const resp = await fetch(CHANNEL_MESSAGE(this.channelID, this.id), {
headers: { let newMsg = await this.client.rest.patch(CHANNEL_MESSAGE(this.channelID, this.id), {
Authorization: `Bot ${this.client.token}`,
'Content-Type': 'application/json'
},
method: 'PATCH',
body: JSON.stringify({
content: text, content: text,
embed: option?.embed.toJSON(), embed: option?.embed.toJSON(),
file: option?.file, file: option?.file,
tts: option?.tts, tts: option?.tts,
allowed_mentions: option?.allowedMention allowed_mentions: option?.allowedMention
}) }) as MessagePayload
})
return new Message(this.client, await resp.json()) return new Message(this.client, newMsg)
} }
// TODO: We have to seperate fetch() // TODO: We have to seperate fetch()
async delete (): Promise<void> { delete (): Promise<void> {
const resp = await fetch(CHANNEL_MESSAGE(this.channelID, this.id), { return this.client.rest.delete(CHANNEL_MESSAGE(this.channelID, this.id)) as any
headers: {
Authorization: `Bot ${this.client.token}`
},
method: 'DELETE'
})
// TODO: improve Error and Promise
return await new Promise((resolve, reject) => {
if (resp.status !== 204) {
reject(new Error())
}
resolve()
})
} }
} }

View file

@ -22,7 +22,7 @@ export class Collection<K, V> extends Map<K, V> {
} }
random() { random() {
let arr = [...this.values()] const arr = [...this.values()]
return arr[Math.floor(Math.random() * arr.length)] return arr[Math.floor(Math.random() * arr.length)]
} }
@ -32,7 +32,7 @@ export class Collection<K, V> extends Map<K, V> {
if (callback(value, key)) return value if (callback(value, key)) return value
} }
// If nothing matched // If nothing matched
return;
} }
filter(callback: (value: V, key: K) => boolean) { filter(callback: (value: V, key: K) => boolean) {