Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(*): use async functions #6210

Merged
merged 5 commits into from
Aug 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 18 additions & 27 deletions src/client/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ class Client extends BaseClient {
);

if (this.options.presence) {
this.options.ws.presence = await this.presence._parse(this.options.presence);
this.options.ws.presence = this.presence._parse(this.options.presence);
}

this.emit(Events.DEBUG, 'Preparing to connect to the gateway...');
Expand Down Expand Up @@ -284,12 +284,10 @@ class Client extends BaseClient {
* .then(invite => console.log(`Obtained invite with code: ${invite.code}`))
* .catch(console.error);
*/
fetchInvite(invite) {
async fetchInvite(invite) {
const code = DataResolver.resolveInviteCode(invite);
return this.api
.invites(code)
.get({ query: { with_counts: true, with_expiration: true } })
.then(data => new Invite(this, data));
const data = await this.api.invites(code).get({ query: { with_counts: true, with_expiration: true } });
return new Invite(this, data);
}

/**
Expand All @@ -301,12 +299,10 @@ class Client extends BaseClient {
* .then(template => console.log(`Obtained template with code: ${template.code}`))
* .catch(console.error);
*/
fetchGuildTemplate(template) {
async fetchGuildTemplate(template) {
const code = DataResolver.resolveGuildTemplateCode(template);
return this.api.guilds
.templates(code)
.get()
.then(data => new GuildTemplate(this, data));
const data = await this.api.guilds.templates(code).get();
return new GuildTemplate(this, data);
}

/**
Expand All @@ -319,11 +315,9 @@ class Client extends BaseClient {
* .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`))
* .catch(console.error);
*/
fetchWebhook(id, token) {
return this.api
.webhooks(id, token)
.get()
.then(data => new Webhook(this, { token, ...data }));
async fetchWebhook(id, token) {
const data = await this.api.webhooks(id, token).get();
return new Webhook(this, { token, ...data });
}

/**
Expand All @@ -334,12 +328,11 @@ class Client extends BaseClient {
* .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`))
* .catch(console.error);
*/
fetchVoiceRegions() {
return this.api.voice.regions.get().then(res => {
const regions = new Collection();
for (const region of res) regions.set(region.id, new VoiceRegion(region));
return regions;
});
async fetchVoiceRegions() {
const apiRegions = await this.api.voice.regions.get();
const regions = new Collection();
for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region));
return regions;
}

/**
Expand Down Expand Up @@ -433,13 +426,11 @@ class Client extends BaseClient {
* @param {GuildResolvable} guild The guild to fetch the preview for
* @returns {Promise<GuildPreview>}
*/
fetchGuildPreview(guild) {
async fetchGuildPreview(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError('INVALID_TYPE', 'guild', 'GuildResolvable');
return this.api
.guilds(id)
.preview.get()
.then(data => new GuildPreview(this, data));
const data = await this.api.guilds(id).preview.get();
return new GuildPreview(this, data);
}

/**
Expand Down
6 changes: 2 additions & 4 deletions src/managers/GuildEmojiManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,8 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
}
}

return this.client.api
.guilds(this.guild.id)
.emojis.post({ data, reason })
.then(emoji => this.client.actions.GuildEmojiCreate.handle(this.guild, emoji).emoji);
const emoji = await this.client.api.guilds(this.guild.id).emojis.post({ data, reason });
return this.client.actions.GuildEmojiCreate.handle(this.guild, emoji).emoji;
}

/**
Expand Down
71 changes: 34 additions & 37 deletions src/managers/GuildManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,45 +195,42 @@ class GuildManager extends CachedManager {
}
if (systemChannelFlags) systemChannelFlags = SystemChannelFlags.resolve(systemChannelFlags);

return new Promise((resolve, reject) =>
this.client.api.guilds
.post({
data: {
name,
icon,
verification_level: verificationLevel,
default_message_notifications: defaultMessageNotifications,
explicit_content_filter: explicitContentFilter,
roles,
channels,
afk_channel_id: afkChannelId,
afk_timeout: afkTimeout,
system_channel_id: systemChannelId,
system_channel_flags: systemChannelFlags,
},
})
.then(data => {
if (this.client.guilds.cache.has(data.id)) return resolve(this.client.guilds.cache.get(data.id));
const data = await this.client.api.guilds.post({
data: {
name,
icon,
verification_level: verificationLevel,
default_message_notifications: defaultMessageNotifications,
explicit_content_filter: explicitContentFilter,
roles,
channels,
afk_channel_id: afkChannelId,
afk_timeout: afkTimeout,
system_channel_id: systemChannelId,
system_channel_flags: systemChannelFlags,
},
});

const handleGuild = guild => {
if (guild.id === data.id) {
clearTimeout(timeout);
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
this.client.decrementMaxListeners();
resolve(guild);
}
};
this.client.incrementMaxListeners();
this.client.on(Events.GUILD_CREATE, handleGuild);
if (this.client.guilds.cache.has(data.id)) return this.client.guilds.cache.get(data.id);

const timeout = setTimeout(() => {
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
this.client.decrementMaxListeners();
resolve(this.client.guilds._add(data));
}, 10000).unref();
return undefined;
}, reject),
);
return new Promise(resolve => {
const handleGuild = guild => {
if (guild.id === data.id) {
clearTimeout(timeout);
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
this.client.decrementMaxListeners();
resolve(guild);
}
};
this.client.incrementMaxListeners();
this.client.on(Events.GUILD_CREATE, handleGuild);

const timeout = setTimeout(() => {
this.client.removeListener(Events.GUILD_CREATE, handleGuild);
this.client.decrementMaxListeners();
resolve(this.client.guilds._add(data));
}, 10000).unref();
});
}

/**
Expand Down
30 changes: 11 additions & 19 deletions src/managers/GuildMemberManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,16 +277,16 @@ class GuildMemberManager extends CachedManager {
* .then(pruned => console.log(`I just pruned ${pruned} people!`))
* .catch(console.error);
*/
prune({ days = 7, dry = false, count: compute_prune_count = true, roles = [], reason } = {}) {
if (typeof days !== 'number') return Promise.reject(new TypeError('PRUNE_DAYS_TYPE'));
async prune({ days = 7, dry = false, count: compute_prune_count = true, roles = [], reason } = {}) {
if (typeof days !== 'number') throw new TypeError('PRUNE_DAYS_TYPE');

const query = { days };
const resolvedRoles = [];

for (const role of roles) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
return Promise.reject(new TypeError('INVALID_ELEMENT', 'Array', 'options.roles', role));
throw new TypeError('INVALID_ELEMENT', 'Array', 'options.roles', role);
}
resolvedRoles.push(resolvedRole);
}
Expand All @@ -297,16 +297,11 @@ class GuildMemberManager extends CachedManager {

const endpoint = this.client.api.guilds(this.guild.id).prune;

if (dry) {
return endpoint.get({ query, reason }).then(data => data.pruned);
}
const { pruned } = await (dry
? endpoint.get({ query, reason })
: endpoint.post({ data: { ...query, compute_prune_count }, reason }));

return endpoint
.post({
data: { ...query, compute_prune_count },
reason,
})
.then(data => data.pruned);
return pruned;
}

/**
Expand Down Expand Up @@ -366,17 +361,14 @@ class GuildMemberManager extends CachedManager {
return this.guild.bans.remove(user, reason);
}

_fetchSingle({ user, cache, force = false }) {
async _fetchSingle({ user, cache, force = false }) {
if (!force) {
const existing = this.cache.get(user);
if (existing && !existing.partial) return Promise.resolve(existing);
if (existing && !existing.partial) return existing;
}

return this.client.api
.guilds(this.guild.id)
.members(user)
.get()
.then(data => this._add(data, cache));
const data = await this.client.api.guilds(this.guild.id).members(user).get();
return this._add(data, cache);
}

_fetchMany({
Expand Down
6 changes: 3 additions & 3 deletions src/managers/GuildStickerManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ class GuildStickerManager extends CachedManager {

const data = { name, tags, description: description ?? '' };

return this.client.api
const sticker = await this.client.api
.guilds(this.guild.id)
.stickers.post({ data, files: [file], reason, dontUsePayloadJSON: true })
.then(sticker => this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker);
.stickers.post({ data, files: [file], reason, dontUsePayloadJSON: true });
return this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker;
}

/**
Expand Down
11 changes: 5 additions & 6 deletions src/managers/MessageManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,11 @@ class MessageManager extends CachedManager {
* .then(messages => console.log(`Received ${messages.size} messages`))
* .catch(console.error);
*/
fetchPinned(cache = true) {
return this.client.api.channels[this.channel.id].pins.get().then(data => {
const messages = new Collection();
for (const message of data) messages.set(message.id, this._add(message, cache));
return messages;
});
async fetchPinned(cache = true) {
const data = await this.client.api.channels[this.channel.id].pins.get();
const messages = new Collection();
for (const message of data) messages.set(message.id, this._add(message, cache));
return messages;
}

/**
Expand Down
6 changes: 4 additions & 2 deletions src/managers/PermissionOverwriteManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ class PermissionOverwriteManager extends CachedManager {
*/
set(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
throw new TypeError('INVALID_TYPE', 'overwrites', 'Array or Collection of Permission Overwrites', true);
return Promise.reject(
new TypeError('INVALID_TYPE', 'overwrites', 'Array or Collection of Permission Overwrites', true),
);
}
return this.channel.edit({ permissionOverwrites: overwrites, reason });
}
Expand All @@ -81,7 +83,7 @@ class PermissionOverwriteManager extends CachedManager {
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!userOrRole) return Promise.reject(new TypeError('INVALID_TYPE', 'parameter', 'User nor a Role'));
if (!userOrRole) throw new TypeError('INVALID_TYPE', 'parameter', 'User nor a Role');
type = userOrRole instanceof Role ? OverwriteTypes.role : OverwriteTypes.member;
}

Expand Down
9 changes: 3 additions & 6 deletions src/managers/ReactionManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,9 @@ class ReactionManager extends CachedManager {
* Removes all reactions from a message.
* @returns {Promise<Message>}
*/
removeAll() {
return this.client.api
.channels(this.message.channel.id)
.messages(this.message.id)
.reactions.delete()
.then(() => this.message);
async removeAll() {
await this.client.api.channels(this.message.channel.id).messages(this.message.id).reactions.delete();
return this.message;
}
}

Expand Down
11 changes: 5 additions & 6 deletions src/managers/ReactionUserManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,14 @@ class ReactionUserManager extends CachedManager {
* @param {UserResolvable} [user=this.client.user] The user to remove the reaction of
* @returns {Promise<MessageReaction>}
*/
remove(user = this.client.user) {
async remove(user = this.client.user) {
const userId = this.client.users.resolveId(user);
if (!userId) return Promise.reject(new Error('REACTION_RESOLVE_USER'));
if (!userId) throw new Error('REACTION_RESOLVE_USER');
const message = this.reaction.message;
return this.client.api.channels[message.channel.id].messages[message.id].reactions[this.reaction.emoji.identifier][
await this.client.api.channels[message.channel.id].messages[message.id].reactions[this.reaction.emoji.identifier][
userId === this.client.user.id ? '@me' : userId
]
.delete()
.then(() => this.reaction);
].delete();
return this.reaction;
}
}

Expand Down
38 changes: 17 additions & 21 deletions src/managers/RoleManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,31 +118,27 @@ class RoleManager extends CachedManager {
* .then(console.log)
* .catch(console.error);
*/
create(options = {}) {
async create(options = {}) {
let { name, color, hoist, permissions, position, mentionable, reason } = options;
if (color) color = resolveColor(color);
if (typeof permissions !== 'undefined') permissions = new Permissions(permissions);

return this.client.api
.guilds(this.guild.id)
.roles.post({
data: {
name,
color,
hoist,
permissions,
mentionable,
},
reason,
})
.then(r => {
const { role } = this.client.actions.GuildRoleCreate.handle({
guild_id: this.guild.id,
role: r,
});
if (position) return role.setPosition(position, reason);
return role;
});
const data = await this.client.api.guilds(this.guild.id).roles.post({
data: {
name,
color,
hoist,
permissions,
mentionable,
},
reason,
});
const { role } = this.client.actions.GuildRoleCreate.handle({
guild_id: this.guild.id,
role: data,
});
if (position) return role.setPosition(position, reason);
return role;
}

/**
Expand Down
Loading