refactor(*): use async functions (#6210)

This commit is contained in:
Sugden
2021-08-02 00:47:43 +01:00
committed by GitHub
parent 626ff85ae7
commit e2e4f6518b
29 changed files with 298 additions and 399 deletions

View File

@@ -556,13 +556,9 @@ class Guild extends AnonymousGuild {
* Resolves with a collection mapping templates by their codes.
* @returns {Promise<Collection<string, GuildTemplate>>}
*/
fetchTemplates() {
return this.client.api
.guilds(this.id)
.templates.get()
.then(templates =>
templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection()),
);
async fetchTemplates() {
const templates = await this.client.api.guilds(this.id).templates.get();
return templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection());
}
/**
@@ -580,22 +576,18 @@ class Guild extends AnonymousGuild {
* @param {string} [description] The description for the template
* @returns {Promise<GuildTemplate>}
*/
createTemplate(name, description) {
return this.client.api
.guilds(this.id)
.templates.post({ data: { name, description } })
.then(data => new GuildTemplate(this.client, data));
async createTemplate(name, description) {
const data = await this.client.api.guilds(this.id).templates.post({ data: { name, description } });
return new GuildTemplate(this.client, data);
}
/**
* Obtains a guild preview for this guild from Discord.
* @returns {Promise<GuildPreview>}
*/
fetchPreview() {
return this.client.api
.guilds(this.id)
.preview.get()
.then(data => new GuildPreview(this.client, data));
async fetchPreview() {
const data = await this.client.api.guilds(this.id).preview.get();
return new GuildPreview(this.client, data);
}
/**
@@ -637,15 +629,11 @@ class Guild extends AnonymousGuild {
* .then(webhooks => console.log(`Fetched ${webhooks.size} webhooks`))
* .catch(console.error);
*/
fetchWebhooks() {
return this.client.api
.guilds(this.id)
.webhooks.get()
.then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
async fetchWebhooks() {
const apiHooks = await this.client.api.guilds(this.id).webhooks.get();
const hooks = new Collection();
for (const hook of apiHooks) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
}
/**
@@ -713,21 +701,19 @@ class Guild extends AnonymousGuild {
* .then(audit => console.log(audit.entries.first()))
* .catch(console.error);
*/
fetchAuditLogs(options = {}) {
async fetchAuditLogs(options = {}) {
if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id;
if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type];
return this.client.api
.guilds(this.id)
['audit-logs'].get({
query: {
before: options.before,
limit: options.limit,
user_id: this.client.users.resolveId(options.user),
action_type: options.type,
},
})
.then(data => GuildAuditLogs.build(this, data));
const data = await this.client.api.guilds(this.id)['audit-logs'].get({
query: {
before: options.before,
limit: options.limit,
user_id: this.client.users.resolveId(options.user),
action_type: options.type,
},
});
return GuildAuditLogs.build(this, data);
}
/**
@@ -781,7 +767,7 @@ class Guild extends AnonymousGuild {
* .then(updated => console.log(`New guild name ${updated}`))
* .catch(console.error);
*/
edit(data, reason) {
async edit(data, reason) {
const _data = {};
if (data.name) _data.name = data.name;
if (typeof data.verificationLevel !== 'undefined') {
@@ -830,10 +816,8 @@ class Guild extends AnonymousGuild {
_data.description = data.description;
}
if (data.preferredLocale) _data.preferred_locale = data.preferredLocale;
return this.client.api
.guilds(this.id)
.patch({ data: _data, reason })
.then(newData => this.client.actions.GuildUpdate.handle(newData).updated);
const newData = await this.client.api.guilds(this.id).patch({ data: _data, reason });
return this.client.actions.GuildUpdate.handle(newData).updated;
}
/**
@@ -1158,7 +1142,7 @@ class Guild extends AnonymousGuild {
* .then(guild => console.log(`Updated channel positions for ${guild}`))
* .catch(console.error);
*/
setChannelPositions(channelPositions) {
async setChannelPositions(channelPositions) {
const updatedChannels = channelPositions.map(r => ({
id: this.client.channels.resolveId(r.channel),
position: r.position,
@@ -1166,16 +1150,11 @@ class Guild extends AnonymousGuild {
parent_id: typeof r.parent !== 'undefined' ? this.channels.resolveId(r.parent) : undefined,
}));
return this.client.api
.guilds(this.id)
.channels.patch({ data: updatedChannels })
.then(
() =>
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: updatedChannels,
}).guild,
);
await this.client.api.guilds(this.id).channels.patch({ data: updatedChannels });
return this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: updatedChannels,
}).guild;
}
/**
@@ -1194,7 +1173,7 @@ class Guild extends AnonymousGuild {
* .then(guild => console.log(`Role positions updated for ${guild}`))
* .catch(console.error);
*/
setRolePositions(rolePositions) {
async setRolePositions(rolePositions) {
// Make sure rolePositions are prepared for API
rolePositions = rolePositions.map(o => ({
id: this.roles.resolveId(o.role),
@@ -1202,18 +1181,13 @@ class Guild extends AnonymousGuild {
}));
// Call the API to update role positions
return this.client.api
.guilds(this.id)
.roles.patch({
data: rolePositions,
})
.then(
() =>
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.id,
roles: rolePositions,
}).guild,
);
await this.client.api.guilds(this.id).roles.patch({
data: rolePositions,
});
return this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.id,
roles: rolePositions,
}).guild;
}
/**
@@ -1222,17 +1196,15 @@ class Guild extends AnonymousGuild {
* @param {string} [reason] Reason for changing the guild's widget settings
* @returns {Promise<Guild>}
*/
setWidgetSettings(settings, reason) {
return this.client.api
.guilds(this.id)
.widget.patch({
data: {
enabled: settings.enabled,
channel_id: this.channels.resolveId(settings.channel),
},
reason,
})
.then(() => this);
async setWidgetSettings(settings, reason) {
await this.client.api.guilds(this.id).widget.patch({
data: {
enabled: settings.enabled,
channel_id: this.channels.resolveId(settings.channel),
},
reason,
});
return this;
}
/**
@@ -1244,13 +1216,10 @@ class Guild extends AnonymousGuild {
* .then(g => console.log(`Left the guild ${g}`))
* .catch(console.error);
*/
leave() {
if (this.ownerId === this.client.user.id) return Promise.reject(new Error('GUILD_OWNED'));
return this.client.api
.users('@me')
.guilds(this.id)
.delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
async leave() {
if (this.ownerId === this.client.user.id) throw new Error('GUILD_OWNED');
await this.client.api.users('@me').guilds(this.id).delete();
return this.client.actions.GuildDelete.handle({ id: this.id }).guild;
}
/**
@@ -1262,11 +1231,9 @@ class Guild extends AnonymousGuild {
* .then(g => console.log(`Deleted the guild ${g}`))
* .catch(console.error);
*/
delete() {
return this.client.api
.guilds(this.id)
.delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
async delete() {
await this.client.api.guilds(this.id).delete();
return this.client.actions.GuildDelete.handle({ id: this.id }).guild;
}
/**

View File

@@ -198,9 +198,10 @@ class GuildAuditLogs {
* Handles possible promises for entry targets.
* @returns {Promise<GuildAuditLogs>}
*/
static build(...args) {
static async build(...args) {
const logs = new GuildAuditLogs(...args);
return Promise.all(logs.entries.map(e => e.target)).then(() => logs);
await Promise.all(logs.entries.map(e => e.target));
return logs;
}
/**
@@ -500,19 +501,17 @@ class GuildAuditLogsEntry {
),
);
} else if (targetType === Targets.INVITE) {
this.target = guild.members.fetch(guild.client.user.id).then(me => {
this.target = guild.members.fetch(guild.client.user.id).then(async me => {
if (me.permissions.has(Permissions.FLAGS.MANAGE_GUILD)) {
let change = this.changes.find(c => c.key === 'code');
change = change.new ?? change.old;
return guild.invites.fetch().then(invites => {
this.target = invites.find(i => i.code === change) ?? null;
});
const invites = await guild.invites.fetch();
this.target = invites.find(i => i.code === change) ?? null;
} else {
this.target = this.changes.reduce((o, c) => {
o[c.key] = c.new ?? c.old;
return o;
}, {});
return this.target;
}
});
} else if (targetType === Targets.MESSAGE) {

View File

@@ -296,18 +296,17 @@ class GuildChannel extends Channel {
if (data.parent) data.parent = this.client.channels.resolveId(data.parent);
if (typeof data.position !== 'undefined') {
await Util.setPosition(
const updatedChannels = await Util.setPosition(
this,
data.position,
false,
this.guild._sortedChannels(this),
this.client.api.guilds(this.guild.id).channels,
reason,
).then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
);
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
}
@@ -389,8 +388,7 @@ class GuildChannel extends Channel {
setParent(channel, { lockPermissions = true, reason } = {}) {
return this.edit(
{
// eslint-disable-next-line no-prototype-builtins
parent: channel ?? null,
parentId: channel?.id ?? channel ?? null,
lockPermissions,
},
reason,
@@ -430,21 +428,20 @@ class GuildChannel extends Channel {
* .then(newChannel => console.log(`Channel's new position is ${newChannel.position}`))
* .catch(console.error);
*/
setPosition(position, { relative, reason } = {}) {
return Util.setPosition(
async setPosition(position, { relative, reason } = {}) {
const updatedChannels = await Util.setPosition(
this,
position,
relative,
this.guild._sortedChannels(this),
this.client.api.guilds(this.guild.id).channels,
reason,
).then(updatedChannels => {
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
return this;
);
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: updatedChannels,
});
return this;
}
/**
@@ -600,11 +597,9 @@ class GuildChannel extends Channel {
* .then(console.log)
* .catch(console.error);
*/
delete(reason) {
return this.client.api
.channels(this.id)
.delete({ reason })
.then(() => this);
async delete(reason) {
await this.client.api.channels(this.id).delete({ reason });
return this;
}
}

View File

@@ -107,9 +107,9 @@ class GuildEmoji extends BaseGuildEmoji {
* .then(e => console.log(`Edited emoji ${e}`))
* .catch(console.error);
*/
edit(data, reason) {
async edit(data, reason) {
const roles = data.roles?.map(r => r.id ?? r);
return this.client.api
const newData = await this.client.api
.guilds(this.guild.id)
.emojis(this.id)
.patch({
@@ -118,12 +118,10 @@ class GuildEmoji extends BaseGuildEmoji {
roles,
},
reason,
})
.then(newData => {
const clone = this._clone();
clone._patch(newData);
return clone;
});
const clone = this._clone();
clone._patch(newData);
return clone;
}
/**
@@ -141,12 +139,9 @@ class GuildEmoji extends BaseGuildEmoji {
* @param {string} [reason] Reason for deleting the emoji
* @returns {Promise<GuildEmoji>}
*/
delete(reason) {
return this.client.api
.guilds(this.guild.id)
.emojis(this.id)
.delete({ reason })
.then(() => this);
async delete(reason) {
await this.client.api.guilds(this.guild.id).emojis(this.id).delete({ reason });
return this;
}
/**

View File

@@ -140,14 +140,10 @@ class GuildPreview extends Base {
* Fetches this guild.
* @returns {Promise<GuildPreview>}
*/
fetch() {
return this.client.api
.guilds(this.id)
.preview.get()
.then(data => {
this._patch(data);
return this;
});
async fetch() {
const data = await this.client.api.guilds(this.id).preview.get();
this._patch(data);
return this;
}
/**

View File

@@ -109,11 +109,10 @@ class GuildTemplate extends Base {
icon: await DataResolver.resolveImage(icon),
},
});
// eslint-disable-next-line consistent-return
return new Promise(resolve => {
const createdGuild = client.guilds.cache.get(data.id);
if (createdGuild) return resolve(createdGuild);
if (client.guilds.cache.has(data.id)) return client.guilds.cache.get(data.id);
return new Promise(resolve => {
const resolveGuild = guild => {
client.off(Events.GUILD_CREATE, handleGuild);
client.decrementMaxListeners();
@@ -146,36 +145,27 @@ class GuildTemplate extends Base {
* @param {EditGuildTemplateOptions} [options] Options for editing the template
* @returns {Promise<GuildTemplate>}
*/
edit({ name, description } = {}) {
return this.client.api
.guilds(this.guildId)
.templates(this.code)
.patch({ data: { name, description } })
.then(data => this._patch(data));
async edit({ name, description } = {}) {
const data = await this.client.api.guilds(this.guildId).templates(this.code).patch({ data: { name, description } });
return this._patch(data);
}
/**
* Deletes this template.
* @returns {Promise<GuildTemplate>}
*/
delete() {
return this.client.api
.guilds(this.guildId)
.templates(this.code)
.delete()
.then(() => this);
async delete() {
await this.client.api.guilds(this.guildId).templates(this.code).delete();
return this;
}
/**
* Syncs this template to the current state of the guild.
* @returns {Promise<GuildTemplate>}
*/
sync() {
return this.client.api
.guilds(this.guildId)
.templates(this.code)
.put()
.then(data => this._patch(data));
async sync() {
const data = await this.client.api.guilds(this.guildId).templates(this.code).put();
return this._patch(data);
}
/**

View File

@@ -126,12 +126,9 @@ class Integration extends Base {
* @returns {Promise<Integration>}
* @param {string} [reason] Reason for deleting this integration
*/
delete(reason) {
return this.client.api
.guilds(this.guild.id)
.integrations(this.id)
.delete({ reason })
.then(() => this);
async delete(reason) {
await this.client.api.guilds(this.guild.id).integrations(this.id).delete({ reason });
return this;
}
toJSON() {

View File

@@ -189,8 +189,9 @@ class Invite extends Base {
* @param {string} [reason] Reason for deleting this invite
* @returns {Promise<Invite>}
*/
delete(reason) {
return this.client.api.invites[this.code].delete({ reason }).then(() => this);
async delete(reason) {
await this.client.api.invites[this.code].delete({ reason });
return this;
}
/**

View File

@@ -637,8 +637,9 @@ class Message extends Base {
* .then(console.log)
* .catch(console.error)
*/
pin() {
return this.channel.messages.pin(this.id).then(() => this);
async pin() {
await this.channel.messages.pin(this.id);
return this;
}
/**
@@ -650,8 +651,9 @@ class Message extends Base {
* .then(console.log)
* .catch(console.error)
*/
unpin() {
return this.channel.messages.unpin(this.id).then(() => this);
async unpin() {
await this.channel.messages.unpin(this.id);
return this;
}
/**

View File

@@ -310,21 +310,20 @@ class Role extends Base {
* .then(updated => console.log(`Role position: ${updated.position}`))
* .catch(console.error);
*/
setPosition(position, { relative, reason } = {}) {
return Util.setPosition(
async setPosition(position, { relative, reason } = {}) {
const updatedRoles = await Util.setPosition(
this,
position,
relative,
this.guild._sortedRoles(),
this.client.api.guilds(this.guild.id).roles,
reason,
).then(updatedRoles => {
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
return this;
);
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: updatedRoles,
});
return this;
}
/**
@@ -337,11 +336,10 @@ class Role extends Base {
* .then(deleted => console.log(`Deleted role ${deleted.name}`))
* .catch(console.error);
*/
delete(reason) {
return this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason }).then(() => {
this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id });
return this;
});
async delete(reason) {
await this.client.api.guilds[this.guild.id].roles[this.id].delete({ reason });
this.client.actions.GuildRoleDelete.handle({ guild_id: this.guild.id, role_id: this.id });
return this;
}
/**

View File

@@ -143,12 +143,11 @@ class TextChannel extends GuildChannel {
* .then(hooks => console.log(`This channel has ${hooks.size} hooks`))
* .catch(console.error);
*/
fetchWebhooks() {
return this.client.api.channels[this.id].webhooks.get().then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
async fetchWebhooks() {
const data = await this.client.api.channels[this.id].webhooks.get();
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
}
/**
@@ -176,15 +175,14 @@ class TextChannel extends GuildChannel {
if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar);
}
return this.client.api.channels[this.id].webhooks
.post({
data: {
name,
avatar,
},
reason,
})
.then(data => new Webhook(this.client, data));
const data = await this.client.api.channels[this.id].webhooks.post({
data: {
name,
avatar,
},
reason,
});
return new Webhook(this.client, data);
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel

View File

@@ -212,16 +212,18 @@ class ThreadChannel extends Channel {
* Makes the client user join the thread.
* @returns {Promise<ThreadChannel>}
*/
join() {
return this.members.add('@me').then(() => this);
async join() {
await this.members.add('@me');
return this;
}
/**
* Makes the client user leave the thread.
* @returns {Promise<ThreadChannel>}
*/
leave() {
return this.members.remove('@me').then(() => this);
async leave() {
await this.members.remove('@me');
return this;
}
/**
@@ -444,11 +446,9 @@ class ThreadChannel extends Channel {
* .then(deletedThread => console.log(deletedThread))
* .catch(console.error);
*/
delete(reason) {
return this.client.api
.channels(this.id)
.delete({ reason })
.then(() => this);
async delete(reason) {
await this.client.api.channels(this.id).delete({ reason });
return this;
}
// These are here only for documentation purposes - they are implemented by TextBasedChannel

View File

@@ -87,8 +87,9 @@ class ThreadMember extends Base {
* @param {string} [reason] Reason for removing the member
* @returns {ThreadMember}
*/
remove(reason) {
return this.thread.members.remove(this.id, reason).then(() => this);
async remove(reason) {
await this.thread.members.remove(this.id, reason);
return this;
}
}

View File

@@ -166,15 +166,13 @@ class Webhook {
}
const { data, files } = await messagePayload.resolveFiles();
return this.client.api
.webhooks(this.id, this.token)
.post({
data,
files,
query: { thread_id: messagePayload.options.threadId, wait: true },
auth: false,
})
.then(d => this.client.channels?.cache.get(d.channel_id)?.messages._add(d, false) ?? d);
const d = await this.client.api.webhooks(this.id, this.token).post({
data,
files,
query: { thread_id: messagePayload.options.threadId, wait: true },
auth: false,
});
return this.client.channels?.cache.get(d.channel_id)?.messages._add(d, false) ?? d;
}
/**
@@ -195,17 +193,15 @@ class Webhook {
* }).catch(console.error);
* @see {@link https://api.slack.com/messaging/webhooks}
*/
sendSlackMessage(body) {
async sendSlackMessage(body) {
if (!this.token) throw new Error('WEBHOOK_TOKEN_UNAVAILABLE');
return this.client.api
.webhooks(this.id, this.token)
.slack.post({
query: { wait: true },
auth: false,
data: body,
})
.then(data => data.toString() === 'ok');
const data = await this.client.api.webhooks(this.id, this.token).slack.post({
query: { wait: true },
auth: false,
data: body,
});
return data.toString() === 'ok';
}
/**

View File

@@ -92,17 +92,13 @@ class Application extends Base {
* Gets the application's rich presence assets.
* @returns {Promise<Array<ApplicationAsset>>}
*/
fetchAssets() {
return this.client.api.oauth2
.applications(this.id)
.assets.get()
.then(assets =>
assets.map(a => ({
id: a.id,
name: a.name,
type: AssetTypes[a.type - 1],
})),
);
async fetchAssets() {
const assets = await this.client.api.oauth2.applications(this.id).assets.get();
return assets.map(a => ({
id: a.id,
name: a.name,
type: AssetTypes[a.type - 1],
}));
}
/**

View File

@@ -155,7 +155,8 @@ class TextBasedChannel {
const GuildMember = require('../GuildMember');
if (this instanceof User || this instanceof GuildMember) {
return this.createDM().then(dm => dm.send(options));
const dm = await this.createDM();
return dm.send(options);
}
let messagePayload;