ChannelManager.js (2538B)
1 'use strict'; 2 3 const BaseManager = require('./BaseManager'); 4 const Channel = require('../structures/Channel'); 5 const { Events } = require('../util/Constants'); 6 7 /** 8 * A manager of channels belonging to a client 9 * @extends {BaseManager} 10 */ 11 class ChannelManager extends BaseManager { 12 constructor(client, iterable) { 13 super(client, iterable, Channel); 14 } 15 16 /** 17 * The cache of Channels 18 * @type {Collection<Snowflake, Channel>} 19 * @name ChannelManager#cache 20 */ 21 22 add(data, guild, cache = true) { 23 const existing = this.cache.get(data.id); 24 if (existing) { 25 if (existing._patch && cache) existing._patch(data); 26 if (guild) guild.channels.add(existing); 27 return existing; 28 } 29 30 const channel = Channel.create(this.client, data, guild); 31 32 if (!channel) { 33 this.client.emit(Events.DEBUG, `Failed to find guild, or unknown type for channel ${data.id} ${data.type}`); 34 return null; 35 } 36 37 if (cache) this.cache.set(channel.id, channel); 38 39 return channel; 40 } 41 42 remove(id) { 43 const channel = this.cache.get(id); 44 if (channel.guild) channel.guild.channels.cache.delete(id); 45 this.cache.delete(id); 46 } 47 48 /** 49 * Data that can be resolved to give a Channel object. This can be: 50 * * A Channel object 51 * * A Snowflake 52 * @typedef {Channel|Snowflake} ChannelResolvable 53 */ 54 55 /** 56 * Resolves a ChannelResolvable to a Channel object. 57 * @method resolve 58 * @memberof ChannelManager 59 * @instance 60 * @param {ChannelResolvable} channel The channel resolvable to resolve 61 * @returns {?Channel} 62 */ 63 64 /** 65 * Resolves a ChannelResolvable to a channel ID string. 66 * @method resolveID 67 * @memberof ChannelManager 68 * @instance 69 * @param {ChannelResolvable} channel The channel resolvable to resolve 70 * @returns {?Snowflake} 71 */ 72 73 /** 74 * Obtains a channel from Discord, or the channel cache if it's already available. 75 * @param {Snowflake} id ID of the channel 76 * @param {boolean} [cache=true] Whether to cache the new channel object if it isn't already 77 * @returns {Promise<Channel>} 78 * @example 79 * // Fetch a channel by its id 80 * client.channels.fetch('222109930545610754') 81 * .then(channel => console.log(channel.name)) 82 * .catch(console.error); 83 */ 84 async fetch(id, cache = true) { 85 const existing = this.cache.get(id); 86 if (existing && !existing.partial) return existing; 87 88 const data = await this.client.api.channels(id).get(); 89 return this.add(data, null, cache); 90 } 91 } 92 93 module.exports = ChannelManager;