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({
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.emit('channelPinsUpdate', before, after)
}

View file

@ -142,7 +142,7 @@ class Gateway {
private async sendIdentify () {
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")
this.debug("Recommended Shards: " + info.shards)
this.debug("=== Session Limit Info ===")

View file

@ -17,7 +17,7 @@ export class BaseManager<T, T2> {
}
get(key: string): T2 | void {
let raw = this._get(key)
const raw = this._get(key)
if(!raw) return
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) {
let cache = this.data[cacheName]
const cache = this.data[cacheName]
if (!cache) return;
return cache.get(key)
}
@ -35,13 +35,13 @@ export class DefaultCacheAdapter implements ICacheAdapter {
}
delete(cacheName: string, key: string) {
let cache = this.data[cacheName]
const cache = this.data[cacheName]
if (!cache) return false
return cache.delete(key)
}
array(cacheName: string) {
let cache = this.data[cacheName]
const cache = this.data[cacheName]
if (!cache) return
return cache.array()
}

View file

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

View file

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

View file

@ -1 +1 @@
//TODO: write code
// TODO: write code

View file

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

View file

@ -22,7 +22,7 @@ export class Collection<K, V> extends Map<K, V> {
}
random() {
let arr = [...this.values()]
const arr = [...this.values()]
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 nothing matched
return;
}
filter(callback: (value: V, key: K) => boolean) {