feat(RoleStore, ChannelStore): fetch() method (#3071)

* feat({Role,Channel}Store): fetch method

* docs: Add usage examples to the new methods

* misc: Add note of why we are fetching all roles even for a single one
This commit is contained in:
Kyra
2019-02-09 16:07:31 +01:00
committed by Amish Shah
parent ae7269088b
commit c432591113
3 changed files with 49 additions and 0 deletions

View File

@@ -74,6 +74,24 @@ class ChannelStore extends DataStore {
super.remove(id);
}
/**
* Obtains a channel from Discord, or the channel cache if it's already available.
* @param {Snowflake} id ID of the channel
* @param {boolean} [cache=true] Whether to cache the new channel object if it isn't already
* @returns {Promise<Channel>}
* @example
* // Fetch a channel by its id
* client.channels.fetch('222109930545610754')
* .then(channel => console.log(channel.name))
* .catch(console.error);
*/
fetch(id, cache = true) {
const existing = this.get(id);
if (existing) return Promise.resolve(existing);
return this.client.api.channels(id).get().then(data => this.add(data, null, cache));
}
/**
* Data that can be resolved to give a Channel object. This can be:
* * A Channel object

View File

@@ -19,6 +19,34 @@ class RoleStore extends DataStore {
return super.add(data, cache, { extras: [this.guild] });
}
/**
* Obtains one or more roles from Discord, or the role cache if they're already available.
* @param {Snowflake} [id] ID or IDs of the role(s)
* @param {boolean} [cache=true] Whether to cache the new roles objects if it weren't already
* @returns {Promise<Role|Role[]>}
* @example
* // Fetch all roles from the guild
* message.guild.roles.fetch()
* .then(roles => console.log(`There are ${roles.size} roles.`))
* .catch(console.error);
* @example
* // Fetch a single role
* message.guild.roles.fetch('222078108977594368')
* .then(role => console.log(`The role color is: ${role.color}`))
* .catch(console.error);
*/
async fetch(id, cache = true) {
if (id) {
const existing = this.get(id);
if (existing) return existing;
}
// We cannot fetch a single role, as of this commit's date, Discord API throws with 405
const roles = await this.client.api.guilds(this.guild.id).roles.get();
for (const role of roles) this.add(role, cache);
return id ? this.get(id) || null : this;
}
/**
* Data that can be resolved to a Role object. This can be:
* * A Role