Skip to content

Commit

Permalink
refactor: new node features (#5132)
Browse files Browse the repository at this point in the history
Co-authored-by: Antonio Román <kyradiscord@gmail.com>
  • Loading branch information
NotSugden and kyranet committed Jun 30, 2021
1 parent f108746 commit 1e8f012
Show file tree
Hide file tree
Showing 68 changed files with 306 additions and 361 deletions.
13 changes: 3 additions & 10 deletions src/client/Client.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,7 @@ class Client extends BaseClient {
constructor(options) {
super(Object.assign({ _tokenType: 'Bot' }, options));

// Obtain shard details from environment or if present, worker threads
let data = process.env;
try {
// Test if worker threads module is present and used
data = require('worker_threads').workerData || data;
} catch {
// Do nothing
}
const data = require('worker_threads').workerData ?? process.env;

if (this.options.shards === DefaultOptions.shards) {
if ('SHARDS' in data) {
Expand Down Expand Up @@ -188,7 +181,7 @@ class Client extends BaseClient {
* @readonly
*/
get readyTimestamp() {
return this.readyAt ? this.readyAt.getTime() : null;
return this.readyAt?.getTime() ?? null;
}

/**
Expand Down Expand Up @@ -341,7 +334,7 @@ class Client extends BaseClient {
channels++;

messages += channel.messages.cache.sweep(
message => now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs,
message => now - (message.editedTimestamp ?? message.createdTimestamp) > lifetimeMs,
);
}

Expand Down
20 changes: 10 additions & 10 deletions src/client/actions/Action.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ class GenericAction {
}

getChannel(data) {
const id = data.channel_id || data.id;
const id = data.channel_id ?? data.id;
return (
data.channel ||
data.channel ??
this.getPayload(
{
id,
guild_id: data.guild_id,
recipients: [data.author || { id: data.user_id }],
recipients: [data.author ?? { id: data.user_id }],
},
this.client.channels,
id,
Expand All @@ -49,14 +49,14 @@ class GenericAction {
}

getMessage(data, channel, cache) {
const id = data.message_id || data.id;
const id = data.message_id ?? data.id;
return (
data.message ||
data.message ??
this.getPayload(
{
id,
channel_id: channel.id,
guild_id: data.guild_id || (channel.guild ? channel.guild.id : null),
guild_id: data.guild_id ?? channel.guild?.id,
},
channel.messages,
id,
Expand All @@ -67,12 +67,12 @@ class GenericAction {
}

getReaction(data, message, user) {
const id = data.emoji.id || decodeURIComponent(data.emoji.name);
const id = data.emoji.id ?? decodeURIComponent(data.emoji.name);
return this.getPayload(
{
emoji: data.emoji,
count: message.partial ? null : 0,
me: user ? user.id === this.client.user.id : false,
me: user?.id === this.client.user.id,
},
message.reactions,
id,
Expand All @@ -86,11 +86,11 @@ class GenericAction {

getUser(data) {
const id = data.user_id;
return data.user || this.getPayload({ id }, this.client.users, id, PartialTypes.USER);
return data.user ?? this.getPayload({ id }, this.client.users, id, PartialTypes.USER);
}

getUserFromMember(data) {
if (data.guild_id && data.member && data.member.user) {
if (data.guild_id && data.member?.user) {
const guild = this.client.guilds.cache.get(data.guild_id);
if (guild) {
return guild.members.add(data.member).user;
Expand Down
2 changes: 1 addition & 1 deletion src/client/actions/ChannelDelete.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ChannelDeleteAction extends Action {

handle(data) {
const client = this.client;
let channel = client.channels.cache.get(data.id);
const channel = client.channels.cache.get(data.id);

if (channel) {
client.channels.remove(channel.id);
Expand Down
2 changes: 1 addition & 1 deletion src/client/actions/GuildDelete.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class GuildDeleteAction extends Action {
this.deleted.set(guild.id, guild);
this.scheduleForDeletion(guild.id);
} else {
guild = this.deleted.get(data.id) || null;
guild = this.deleted.get(data.id) ?? null;
}

return { guild };
Expand Down
2 changes: 1 addition & 1 deletion src/client/actions/GuildEmojisUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const Action = require('./Action');
class GuildEmojisUpdateAction extends Action {
handle(data) {
const guild = this.client.guilds.cache.get(data.guild_id);
if (!guild || !guild.emojis) return;
if (!guild?.emojis) return;

const deletions = new Map(guild.emojis.cache);

Expand Down
2 changes: 1 addition & 1 deletion src/client/actions/MessageCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class MessageCreateAction extends Action {
if (existing) return { message: existing };
const message = channel.messages.add(data);
const user = message.author;
let member = message.member;
const member = message.member;
channel.lastMessageID = data.id;
if (user) {
user.lastMessageID = data.id;
Expand Down
4 changes: 2 additions & 2 deletions src/client/actions/MessageReactionAdd.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ class MessageReactionAdd extends Action {

// Verify reaction
if (message.partial && !this.client.options.partials.includes(PartialTypes.REACTION)) return false;
const existing = message.reactions.cache.get(data.emoji.id || data.emoji.name);
if (existing && existing.users.cache.has(user.id)) return { message, reaction: existing, user };
const existing = message.reactions.cache.get(data.emoji.id ?? data.emoji.name);
if (existing?.users.cache.has(user.id)) return { message, reaction: existing, user };
const reaction = message.reactions.add({
emoji: data.emoji,
count: message.partial ? null : 0,
Expand Down
2 changes: 1 addition & 1 deletion src/client/actions/MessageReactionRemoveEmoji.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class MessageReactionRemoveEmoji extends Action {

const reaction = this.getReaction(data, message);
if (!reaction) return false;
if (!message.partial) message.reactions.cache.delete(reaction.emoji.id || reaction.emoji.name);
if (!message.partial) message.reactions.cache.delete(reaction.emoji.id ?? reaction.emoji.name);

/**
* Emitted when a bot removes an emoji reaction from a cached message.
Expand Down
9 changes: 4 additions & 5 deletions src/client/actions/PresenceUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@ const { Events } = require('../../util/Constants');
class PresenceUpdateAction extends Action {
handle(data) {
let user = this.client.users.cache.get(data.user.id);
if (!user && data.user.username) user = this.client.users.add(data.user);
if (!user && data.user?.username) user = this.client.users.add(data.user);
if (!user) return;

if (data.user && data.user.username) {
if (data.user?.username) {
if (!user.equals(data.user)) this.client.actions.UserUpdate.handle(data.user);
}

const guild = this.client.guilds.cache.get(data.guild_id);
if (!guild) return;

let oldPresence = guild.presences.cache.get(user.id);
if (oldPresence) oldPresence = oldPresence._clone();
const oldPresence = guild.presences.cache.get(user.id)?._clone();
let member = guild.members.cache.get(user.id);
if (!member && data.status !== 'offline') {
member = guild.members.add({
Expand All @@ -28,7 +27,7 @@ class PresenceUpdateAction extends Action {
this.client.emit(Events.GUILD_MEMBER_AVAILABLE, member);
}
guild.presences.add(Object.assign(data, { guild }));
if (member && this.client.listenerCount(Events.PRESENCE_UPDATE) && !member.presence.equals(oldPresence)) {
if (this.client.listenerCount(Events.PRESENCE_UPDATE) && member && !member.presence.equals(oldPresence)) {
/**
* Emitted whenever a guild member's presence (e.g. status, activity) is changed.
* @event Client#presenceUpdate
Expand Down
9 changes: 4 additions & 5 deletions src/client/actions/VoiceStateUpdate.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,21 @@ class VoiceStateUpdate extends Action {
if (guild) {
const VoiceState = Structures.get('VoiceState');
// Update the state
const oldState = guild.voiceStates.cache.has(data.user_id)
? guild.voiceStates.cache.get(data.user_id)._clone()
: new VoiceState(guild, { user_id: data.user_id });
const oldState =
guild.voiceStates.cache.get(data.user_id)?._clone() ?? new VoiceState(guild, { user_id: data.user_id });

const newState = guild.voiceStates.add(data);

// Get the member
let member = guild.members.cache.get(data.user_id);
if (member && data.member) {
member._patch(data.member);
} else if (data.member && data.member.user && data.member.joined_at) {
} else if (data.member?.user && data.member.joined_at) {
member = guild.members.add(data.member);
}

// Emit event
if (member && member.user.id === client.user.id) {
if (member?.user.id === client.user.id) {
client.emit('debug', `[VOICE] received voice state update: ${JSON.stringify(data)}`);
client.voice.onVoiceStateUpdate(data);
}
Expand Down
2 changes: 1 addition & 1 deletion src/client/websocket/WebSocketManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ class WebSocketManager extends EventEmitter {
try {
await shard.connect();
} catch (error) {
if (error && error.code && UNRECOVERABLE_CLOSE_CODES.includes(error.code)) {
if (error?.code && UNRECOVERABLE_CLOSE_CODES.includes(error.code)) {
throw new Error(WSCodes[error.code]);
// Undefined if session is invalid, error event for regular closes
} else if (!error || error.code) {
Expand Down
10 changes: 5 additions & 5 deletions src/client/websocket/WebSocketShard.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ class WebSocketShard extends EventEmitter {
connect() {
const { gateway, client } = this.manager;

if (this.connection && this.connection.readyState === WebSocket.OPEN && this.status === Status.READY) {
if (this.connection?.readyState === WebSocket.OPEN && this.status === Status.READY) {
return Promise.resolve();
}

Expand Down Expand Up @@ -216,7 +216,7 @@ class WebSocketShard extends EventEmitter {
this.once(ShardEvents.INVALID_SESSION, onInvalidOrDestroyed);
this.once(ShardEvents.DESTROYED, onInvalidOrDestroyed);

if (this.connection && this.connection.readyState === WebSocket.OPEN) {
if (this.connection?.readyState === WebSocket.OPEN) {
this.debug('An open connection was found, attempting an immediate identify.');
this.identify();
return;
Expand Down Expand Up @@ -306,7 +306,7 @@ class WebSocketShard extends EventEmitter {
* @private
*/
onError(event) {
const error = event && event.error ? event.error : event;
const error = event?.error ?? event;
if (!error) return;

/**
Expand Down Expand Up @@ -345,7 +345,7 @@ class WebSocketShard extends EventEmitter {
this.debug(`[CLOSE]
Event Code: ${event.code}
Clean : ${event.wasClean}
Reason : ${event.reason || 'No reason received'}`);
Reason : ${event.reason ?? 'No reason received'}`);

this.setHeartbeatTimer(-1);
this.setHelloTimeout(-1);
Expand Down Expand Up @@ -648,7 +648,7 @@ class WebSocketShard extends EventEmitter {
* @private
*/
_send(data) {
if (!this.connection || this.connection.readyState !== WebSocket.OPEN) {
if (this.connection?.readyState !== WebSocket.OPEN) {
this.debug(`Tried to send packet '${JSON.stringify(data)}' but no WebSocket is available!`);
this.destroy({ closeCode: 4000 });
return;
Expand Down
2 changes: 1 addition & 1 deletion src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = (client, { d: data }) => {

if (channel && !Number.isNaN(time.getTime())) {
// Discord sends null for last_pin_timestamp if the last pinned message was removed
channel.lastPinTimestamp = time.getTime() || null;
channel.lastPinTimestamp = time.getTime() ?? null;

/**
* Emitted whenever the pins of a channel are updated. Due to the nature of the WebSocket event,
Expand Down
2 changes: 1 addition & 1 deletion src/errors/DJSError.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function message(key, args) {
const msg = messages.get(key);
if (!msg) throw new Error(`An invalid error message key was used: ${key}.`);
if (typeof msg === 'function') return msg(...args);
if (args === undefined || args.length === 0) return msg;
if (!args?.length) return msg;
args.unshift(msg);
return String(...args);
}
Expand Down
6 changes: 2 additions & 4 deletions src/managers/ApplicationCommandManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class ApplicationCommandManager extends BaseManager {
*/
commandPath({ id, guildID } = {}) {
let path = this.client.api.applications(this.client.application.id);
if (this.guild || guildID) path = path.guilds(this.guild?.id ?? guildID);
if (this.guild ?? guildID) path = path.guilds(this.guild?.id ?? guildID);
return id ? path.commands(id) : path.commands;
}

Expand Down Expand Up @@ -84,9 +84,7 @@ class ApplicationCommandManager extends BaseManager {
async fetch(id, { guildID, cache = true, force = false } = {}) {
if (typeof id === 'object') {
({ guildID, cache = true, force = false } = id);
id = undefined;
}
if (id) {
} else if (id) {
if (!force) {
const existing = this.cache.get(id);
if (existing) return existing;
Expand Down
2 changes: 1 addition & 1 deletion src/managers/BaseGuildEmojiManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class BaseGuildEmojiManager extends BaseManager {
if (emoji instanceof ReactionEmoji) return emoji.identifier;
if (typeof emoji === 'string') {
const res = parseEmoji(emoji);
if (res && res.name.length) {
if (res?.name.length) {
emoji = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`;
}
if (!emoji.includes('%')) return encodeURIComponent(emoji);
Expand Down
10 changes: 5 additions & 5 deletions src/managers/BaseManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class BaseManager {
* @private
* @readonly
*/
Object.defineProperty(this, 'holds', { value: Structures.get(holds.name) || holds });
Object.defineProperty(this, 'holds', { value: Structures.get(holds.name) ?? holds });

/**
* The client that instantiated this Manager
Expand All @@ -42,12 +42,12 @@ class BaseManager {
}

add(data, cache = true, { id, extras = [] } = {}) {
const existing = this.cache.get(id || data.id);
if (existing && existing._patch && cache) existing._patch(data);
const existing = this.cache.get(id ?? data.id);
if (cache) existing?._patch(data);
if (existing) return existing;

const entry = this.holds ? new this.holds(this.client, data, ...extras) : data;
if (cache) this.cache.set(id || entry.id, entry);
if (cache) this.cache.set(id ?? entry.id, entry);
return entry;
}

Expand All @@ -58,7 +58,7 @@ class BaseManager {
*/
resolve(idOrInstance) {
if (idOrInstance instanceof this.holds) return idOrInstance;
if (typeof idOrInstance === 'string') return this.cache.get(idOrInstance) || null;
if (typeof idOrInstance === 'string') return this.cache.get(idOrInstance) ?? null;
return null;
}

Expand Down
8 changes: 4 additions & 4 deletions src/managers/ChannelManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ class ChannelManager extends BaseManager {
add(data, guild, cache = true) {
const existing = this.cache.get(data.id);
if (existing) {
if (existing._patch && cache) existing._patch(data);
if (guild) guild.channels?.add(existing);
if (ThreadChannelTypes.includes(existing.type) && typeof existing.parent?.threads !== 'undefined') {
existing.parent.threads.add(existing);
if (cache) existing._patch(data);
guild?.channels?.add(existing);
if (ThreadChannelTypes.includes(existing.type)) {
existing.parent?.threads?.add(existing);
}
return existing;
}
Expand Down
7 changes: 4 additions & 3 deletions src/managers/GuildChannelManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,10 @@ class GuildChannelManager extends BaseManager {
* ],
* })
*/
async create(name, options = {}) {
let { type, topic, nsfw, bitrate, userLimit, parent, permissionOverwrites, position, rateLimitPerUser, reason } =
options;
async create(
name,
{ type, topic, nsfw, bitrate, userLimit, parent, permissionOverwrites, position, rateLimitPerUser, reason } = {},
) {
if (parent) parent = this.client.channels.resolveID(parent);
if (permissionOverwrites) {
permissionOverwrites = permissionOverwrites.map(o => PermissionOverwrites.resolve(o, this.guild));
Expand Down
4 changes: 2 additions & 2 deletions src/managers/GuildMemberManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ class GuildMemberManager extends BaseManager {
* @example
* // Kick a user by ID (or with a user/guild member object)
* guild.members.kick('84484653687267328')
* .then(user => console.log(`Kicked ${user.username || user.id || user} from ${guild.name}`))
* .then(user => console.log(`Kicked ${user.username ?? user.id ?? user} from ${guild.name}`))
* .catch(console.error);
*/
async kick(user, reason) {
Expand Down Expand Up @@ -356,7 +356,7 @@ class GuildMemberManager extends BaseManager {
},
});
const fetchedMembers = new Collection();
const option = query || limit || presences || user_ids;
const option = Boolean(query || limit || presences || user_ids);
let i = 0;
const handler = (members, _, chunk) => {
timeout.refresh();
Expand Down

0 comments on commit 1e8f012

Please sign in to comment.