Skip to content

Commit

Permalink
refactor: remove parameter reassignment
Browse files Browse the repository at this point in the history
  • Loading branch information
sdanialraza committed Jan 19, 2025
1 parent aa90f00 commit 7380a7b
Show file tree
Hide file tree
Showing 22 changed files with 208 additions and 185 deletions.
1 change: 1 addition & 0 deletions packages/discord.js/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error",
"no-param-reassign": "error",

"no-restricted-globals": [
"error",
Expand Down
5 changes: 3 additions & 2 deletions packages/discord.js/src/managers/ApplicationEmojiManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ class ApplicationEmojiManager extends CachedManager {
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
*/
async create({ attachment, name }) {
attachment = await resolveImage(attachment);
async create(options) {
const { attachment: rawAttachment, name } = options;
const attachment = await resolveImage(rawAttachment);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);

const body = { image: attachment, name };
Expand Down
7 changes: 4 additions & 3 deletions packages/discord.js/src/managers/BaseGuildEmojiManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,12 @@ class BaseGuildEmojiManager extends CachedManager {
if (emoji instanceof ApplicationEmoji) return emoji.identifier;
if (typeof emoji === 'string') {
const res = parseEmoji(emoji);
let identifier = emoji;
if (res?.name.length) {
emoji = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`;
identifier = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`;
}
if (!emoji.includes('%')) return encodeURIComponent(emoji);
return emoji;
if (!identifier.includes('%')) return encodeURIComponent(identifier);
return identifier;
}
return null;
}
Expand Down
47 changes: 25 additions & 22 deletions packages/discord.js/src/managers/GuildChannelManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ class GuildChannelManager extends CachedManager {
* @readonly
*/
get channelCountWithoutThreads() {
return this.cache.reduce((acc, channel) => {
if (ThreadChannelTypes.includes(channel.type)) return acc;
return ++acc;
}, 0);
return this.cache.filter(channel => !ThreadChannelTypes.includes(channel.type)).size;
}

/**
Expand Down Expand Up @@ -184,9 +181,6 @@ class GuildChannelManager extends CachedManager {
defaultForumLayout,
reason,
}) {
parent &&= this.client.channels.resolveId(parent);
permissionOverwrites &&= permissionOverwrites.map(overwrite => PermissionOverwrites.resolve(overwrite, this.guild));

const data = await this.client.rest.post(Routes.guildChannels(this.guild.id), {
body: {
name,
Expand All @@ -195,9 +189,11 @@ class GuildChannelManager extends CachedManager {
nsfw,
bitrate,
user_limit: userLimit,
parent_id: parent,
parent_id: parent && this.client.channels.resolveId(parent),
position,
permission_overwrites: permissionOverwrites,
permission_overwrites: permissionOverwrites?.map(overwrite =>
PermissionOverwrites.resolve(overwrite, this.guild),
),
rate_limit_per_user: rateLimitPerUser,
rtc_region: rtcRegion,
video_quality_mode: videoQualityMode,
Expand Down Expand Up @@ -235,18 +231,22 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error)
*/
async createWebhook({ channel, name, avatar, reason }) {
const id = this.resolveId(channel);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const channelId = this.resolveId(channel);
if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');

let resolvedAvatar;
if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await resolveImage(avatar);
resolvedAvatar = await resolveImage(avatar);
}
const data = await this.client.rest.post(Routes.channelWebhooks(id), {

const data = await this.client.rest.post(Routes.channelWebhooks(channelId), {
body: {
name,
avatar,
avatar: resolvedAvatar ?? avatar,
},
reason,
});

return new Webhook(this.client, data);
}

Expand Down Expand Up @@ -361,13 +361,14 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error);
*/
async setPosition(channel, position, { relative, reason } = {}) {
channel = this.resolve(channel);
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const resolvedChannel = this.resolve(channel);
if (!resolvedChannel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');

const updatedChannels = await setPosition(
channel,
resolvedChannel,
position,
relative,
this.guild._sortedChannels(channel),
this.guild._sortedChannels(resolvedChannel),
this.client,
Routes.guildChannels(this.guild.id),
reason,
Expand All @@ -377,7 +378,8 @@ class GuildChannelManager extends CachedManager {
guild_id: this.guild.id,
channels: updatedChannels,
});
return channel;

return resolvedChannel;
}

/**
Expand Down Expand Up @@ -459,17 +461,18 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error);
*/
async setPositions(channelPositions) {
channelPositions = channelPositions.map(channelPosition => ({
const resolvedChannelPositions = channelPositions.map(channelPosition => ({
id: this.client.channels.resolveId(channelPosition.channel),
position: channelPosition.position,
lock_permissions: channelPosition.lockPermissions,
parent_id: channelPosition.parent !== undefined ? this.resolveId(channelPosition.parent) : undefined,
}));

await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: channelPositions });
await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: resolvedChannelPositions });

return this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: channelPositions,
channels: resolvedChannelPositions,
}).guild;
}

Expand Down
17 changes: 9 additions & 8 deletions packages/discord.js/src/managers/GuildEmojiManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
*/
async create({ attachment, name, roles, reason }) {
attachment = await resolveImage(attachment);
async create(options) {
const { attachment: rawAttachment, name, roles, reason } = options;
const attachment = await resolveImage(rawAttachment);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);

const body = { image: attachment, name };
Expand Down Expand Up @@ -153,9 +154,9 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
* @returns {Promise<User>}
*/
async fetchAuthor(emoji) {
emoji = this.resolve(emoji);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (emoji.managed) {
const resolvedEmoji = this.resolve(emoji);
if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (resolvedEmoji.managed) {
throw new DiscordjsError(ErrorCodes.EmojiManaged);
}

Expand All @@ -165,9 +166,9 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
throw new DiscordjsError(ErrorCodes.MissingManageGuildExpressionsPermission, this.guild);
}

const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, emoji.id));
emoji._patch(data);
return emoji.author;
const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, resolvedEmoji.id));
resolvedEmoji._patch(data);
return resolvedEmoji.author;
}
}

Expand Down
12 changes: 8 additions & 4 deletions packages/discord.js/src/managers/GuildEmojiRoleManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ class GuildEmojiRoleManager extends DataManager {
* @returns {Promise<GuildEmoji>}
*/
add(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
let roles;
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roles = [roleOrRoles];
else roles = roleOrRoles;

const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
for (const role of roles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
Expand All @@ -61,10 +63,12 @@ class GuildEmojiRoleManager extends DataManager {
* @returns {Promise<GuildEmoji>}
*/
remove(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
let roles;
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roles = [roleOrRoles];
else roles = roleOrRoles;

const resolvedRoleIds = [];
for (const role of roleOrRoles.values()) {
for (const role of roles.values()) {
const roleId = this.guild.roles.resolveId(role);
if (!roleId) {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
Expand Down
21 changes: 12 additions & 9 deletions packages/discord.js/src/managers/GuildMemberManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,18 +223,21 @@ class GuildMemberManager extends CachedManager {
return this._add(data, cache);
}

_fetchMany({
limit = 0,
withPresences: presences,
users,
query,
time = 120e3,
nonce = DiscordSnowflake.generate().toString(),
} = {}) {
_fetchMany(options = {}) {
const {
limit = 0,
withPresences: presences,
users,
query: initialQuery,
time = 120e3,
nonce = DiscordSnowflake.generate().toString(),
} = options;

if (nonce.length > 32) return Promise.reject(new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength));

const query = initialQuery || (!users ? '' : undefined);

return new Promise((resolve, reject) => {
if (!query && !users) query = '';
this.guild.client.ws.send(this.guild.shardId, {
op: GatewayOpcodes.RequestGuildMembers,
d: {
Expand Down
16 changes: 8 additions & 8 deletions packages/discord.js/src/managers/GuildMemberRoleManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,19 +121,19 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = [...new Set(resolvedRoles.concat(...this.cache.keys()))];
return this.set(newRoles, reason);
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (resolvedRoleId === null) {
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',
);
}

await this.client.rest.put(Routes.guildMemberRole(this.guild.id, this.member.id, roleOrRoles), { reason });
await this.client.rest.put(Routes.guildMemberRole(this.guild.id, this.member.id, resolvedRoleId), { reason });

const clone = this.member._clone();
clone._roles = [...this.cache.keys(), roleOrRoles];
clone._roles = [...this.cache.keys(), resolvedRoleId];
return clone;
}
}
Expand All @@ -160,19 +160,19 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = this.cache.filter(role => !resolvedRoles.includes(role.id));
return this.set(newRoles, reason);
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (resolvedRoleId === null) {
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',
);
}

await this.client.rest.delete(Routes.guildMemberRole(this.guild.id, this.member.id, roleOrRoles), { reason });
await this.client.rest.delete(Routes.guildMemberRole(this.guild.id, this.member.id, resolvedRoleId), { reason });

const clone = this.member._clone();
const newRoles = this.cache.filter(role => role.id !== roleOrRoles);
const newRoles = this.cache.filter(role => role.id !== resolvedRoleId);
clone._roles = [...newRoles.keys()];
return clone;
}
Expand Down
22 changes: 11 additions & 11 deletions packages/discord.js/src/managers/GuildStickerManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,16 @@ class GuildStickerManager extends CachedManager {
* .catch(console.error);
*/
async create({ file, name, tags, description, reason } = {}) {
const resolvedFile = await MessagePayload.resolveFile(file);
let resolvedFile = await MessagePayload.resolveFile(file);
if (!resolvedFile) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
file = { ...resolvedFile, key: 'file' };
resolvedFile = { ...resolvedFile, key: 'file' };

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

const sticker = await this.client.rest.post(Routes.guildStickers(this.guild.id), {
appendToFormData: true,
body,
files: [file],
files: [resolvedFile],
reason,
});
return this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker;
Expand Down Expand Up @@ -129,10 +129,10 @@ class GuildStickerManager extends CachedManager {
* @returns {Promise<void>}
*/
async delete(sticker, reason) {
sticker = this.resolveId(sticker);
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const resolvedStickerId = this.resolveId(sticker);
if (!resolvedStickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');

await this.client.rest.delete(Routes.guildSticker(this.guild.id, sticker), { reason });
await this.client.rest.delete(Routes.guildSticker(this.guild.id, resolvedStickerId), { reason });
}

/**
Expand Down Expand Up @@ -171,11 +171,11 @@ class GuildStickerManager extends CachedManager {
* @returns {Promise<?User>}
*/
async fetchUser(sticker) {
sticker = this.resolve(sticker);
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, sticker.id));
sticker._patch(data);
return sticker.user;
const resolvedSticker = this.resolve(sticker);
if (!resolvedSticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, resolvedSticker.id));
resolvedSticker._patch(data);
return resolvedSticker.user;
}
}

Expand Down
Loading

0 comments on commit 7380a7b

Please sign in to comment.