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 b02b759
Show file tree
Hide file tree
Showing 20 changed files with 172 additions and 152 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
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
34 changes: 17 additions & 17 deletions packages/discord.js/src/managers/MessageManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async pin(message, reason) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');

await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
await this.client.rest.put(Routes.channelPin(this.channel.id, messageId), { reason });
}

/**
Expand All @@ -216,10 +216,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async unpin(message, reason) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');

await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
await this.client.rest.delete(Routes.channelPin(this.channel.id, messageId), { reason });
}

/**
Expand All @@ -229,17 +229,17 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async react(message, emoji) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');

emoji = resolvePartialEmoji(emoji);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const resolvedEmoji = resolvePartialEmoji(emoji);
if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');

const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
: encodeURIComponent(emoji.name);
const emojiId = resolvedEmoji.id
? `${resolvedEmoji.animated ? 'a:' : ''}${resolvedEmoji.name}:${resolvedEmoji.id}`
: encodeURIComponent(resolvedEmoji.name);

await this.client.rest.put(Routes.channelMessageOwnReaction(this.channel.id, message, emojiId));
await this.client.rest.put(Routes.channelMessageOwnReaction(this.channel.id, messageId, emojiId));
}

/**
Expand All @@ -248,10 +248,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async delete(message) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');

await this.client.rest.delete(Routes.channelMessage(this.channel.id, message));
await this.client.rest.delete(Routes.channelMessage(this.channel.id, messageId));
}

/**
Expand Down
14 changes: 8 additions & 6 deletions packages/discord.js/src/managers/PermissionOverwriteManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,14 @@ class PermissionOverwriteManager extends CachedManager {
* @private
*/
async upsert(userOrRole, options, overwriteOptions = {}, existing) {
let userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
const resolvedUserOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
const { reason, type } = overwriteOptions;
let resolvedType = type;

if (typeof resolvedType !== 'number') {
if (!resolvedUserOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
resolvedType = resolvedUserOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
}

const { allow, deny } = PermissionOverwrites.resolveOverwriteOptions(options, existing);
Expand Down
27 changes: 15 additions & 12 deletions packages/discord.js/src/managers/RoleManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,11 @@ class RoleManager extends CachedManager {
* .catch(console.error);
*/
async edit(role, options) {
role = this.resolve(role);
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const resolvedRole = this.resolve(role);
if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');

if (typeof options.position === 'number') {
await this.setPosition(role, options.position, { reason: options.reason });
await this.setPosition(resolvedRole, options.position, { reason: options.reason });
}

let icon = options.icon;
Expand All @@ -210,9 +210,12 @@ class RoleManager extends CachedManager {
unicode_emoji: options.unicodeEmoji,
};

const d = await this.client.rest.patch(Routes.guildRole(this.guild.id, role.id), { body, reason: options.reason });
const d = await this.client.rest.patch(Routes.guildRole(this.guild.id, resolvedRole.id), {
body,
reason: options.reason,
});

const clone = role._clone();
const clone = resolvedRole._clone();
clone._patch(d);
return clone;
}
Expand Down Expand Up @@ -247,10 +250,10 @@ class RoleManager extends CachedManager {
* .catch(console.error);
*/
async setPosition(role, position, { relative, reason } = {}) {
role = this.resolve(role);
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const resolvedRole = this.resolve(role);
if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const updatedRoles = await setPosition(
role,
resolvedRole,
position,
relative,
this.guild._sortedRoles(),
Expand All @@ -263,7 +266,7 @@ class RoleManager extends CachedManager {
guild_id: this.guild.id,
roles: updatedRoles,
});
return role;
return resolvedRole;
}

/**
Expand All @@ -284,16 +287,16 @@ class RoleManager extends CachedManager {
*/
async setPositions(rolePositions) {
// Make sure rolePositions are prepared for API
rolePositions = rolePositions.map(rolePosition => ({
const resolvedRolePositions = rolePositions.map(rolePosition => ({
id: this.resolveId(rolePosition.role),
position: rolePosition.position,
}));

// Call the API to update role positions
await this.client.rest.patch(Routes.guildRoles(this.guild.id), { body: rolePositions });
await this.client.rest.patch(Routes.guildRoles(this.guild.id), { body: resolvedRolePositions });
return this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: rolePositions,
roles: resolvedRolePositions,
}).guild;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/sharding/ShardClientUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,18 +134,18 @@ class ShardClientUtil {
reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
return;
}
script = `(${script})(this, ${JSON.stringify(options.context)})`;
const evalScript = `(${script})(this, ${JSON.stringify(options.context)})`;

const listener = message => {
if (message?._sEval !== script || message._sEvalShard !== options.shard) return;
if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) return;
parent.removeListener('message', listener);
this.decrementMaxListeners(parent);
if (!message._error) resolve(message._result);
else reject(makeError(message._error));
};
this.incrementMaxListeners(parent);
parent.on('message', listener);
this.send({ _sEval: script, _sEvalShard: options.shard }).catch(err => {
this.send({ _sEval: evalScript, _sEvalShard: options.shard }).catch(err => {
parent.removeListener('message', listener);
this.decrementMaxListeners(parent);
reject(err);
Expand Down
Loading

0 comments on commit b02b759

Please sign in to comment.