fix: remove get query loop loop de loop loop

This commit is contained in:
Skillz4Killz
2022-03-26 00:11:47 +00:00
committed by GitHub
parent 80d2e94840
commit b06f6d2512
15 changed files with 126 additions and 81 deletions

View File

@@ -10,21 +10,23 @@ export async function getArchivedThreads(
type?: "public" | "private" | "privateJoinedThreads";
},
) {
let url = options?.type === "privateJoinedThreads"
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE_JOINED(channelId)
: options?.type === "private"
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE(channelId)
: bot.constants.endpoints.THREAD_ARCHIVED_PUBLIC(channelId);
if (options) {
url += "?";
if (options.before) url += `before=${options.before}`;
if (options.limit) url += `&limit=${options.limit}`;
if (options.type) url += `&type=${options.type}`;
}
const result = (await bot.rest.runMethod<DiscordListActiveThreads>(
bot.rest,
"get",
options?.type === "privateJoinedThreads"
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE_JOINED(channelId)
: options?.type === "private"
? bot.constants.endpoints.THREAD_ARCHIVED_PRIVATE(channelId)
: bot.constants.endpoints.THREAD_ARCHIVED_PUBLIC(channelId),
options
? {
before: options.before,
limit: options.limit,
type: options.type,
}
: {},
url,
));
return {

View File

@@ -5,8 +5,7 @@ export async function validDiscoveryTerm(bot: Bot, term: string) {
const result = await bot.rest.runMethod<DiscordValidateDiscoverySearchTerm>(
bot.rest,
"get",
bot.constants.endpoints.DISCOVERY_VALID_TERM(),
{ term },
`${bot.constants.endpoints.DISCOVERY_VALID_TERM()}?term=${term}`,
);
return result.valid;

View File

@@ -4,15 +4,21 @@ import { AuditLogEvents } from "../../types/shared.ts";
/** Returns the audit logs for the guild. Requires VIEW AUDIT LOGS permission */
export async function getAuditLogs(bot: Bot, guildId: bigint, options?: GetGuildAuditLog) {
if (options?.userId) options.userId = options.userId.toString();
if (options?.before) options.before = options.before.toString();
if (options?.limit) options.limit = options.limit >= 1 && options.limit <= 100 ? options.limit : 50;
let url = bot.constants.endpoints.GUILD_AUDIT_LOGS(guildId);
if (options) {
url += "?";
if (options.actionType) url += `action_type=${options.actionType}`;
if (options.before) url += `&before=${options.before}`;
if (options.limit) url += `&limit=${options.limit}`;
if (options.userId) url += `&user_id=${options.userId}`;
}
const auditlog = await bot.rest.runMethod<DiscordAuditLog>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_AUDIT_LOGS(guildId),
options,
url,
);
return {

View File

@@ -12,9 +12,11 @@ export async function getGuild(
counts: true,
},
) {
const result = await bot.rest.runMethod<DiscordGuild>(bot.rest, "get", bot.constants.endpoints.GUILDS_BASE(guildId), {
with_counts: options.counts,
});
const result = await bot.rest.runMethod<DiscordGuild>(
bot.rest,
"get",
`${bot.constants.endpoints.GUILDS_BASE(guildId)}?with_counts=${options.counts ?? false}`,
);
return bot.transformers.guild(bot, {
guild: result,

View File

@@ -7,16 +7,19 @@ export async function getPruneCount(bot: Bot, guildId: bigint, options?: GetGuil
throw new Error(bot.constants.Errors.PRUNE_MAX_DAYS);
}
let url = bot.constants.endpoints.GUILD_PRUNE(guildId);
if (options) {
url += "?";
if (options.days) url += `days=${options.days}`;
if (options.includeRoles) url += `&include_roles=${options.includeRoles}`;
}
const result = await bot.rest.runMethod(
bot.rest,
"get",
bot.constants.endpoints.GUILD_PRUNE(guildId),
options
? {
days: options.days,
include_roles: options.includeRoles,
}
: {},
url,
);
return result.pruned as number;

View File

@@ -11,8 +11,9 @@ export async function getScheduledEvent(
const event = await bot.rest.runMethod<DiscordScheduledEvent>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_SCHEDULED_EVENT(guildId, eventId),
{ with_user_count: options?.withUserCount || false },
`${bot.constants.endpoints.GUILD_SCHEDULED_EVENT(guildId, eventId)}?with_user_count=${
options?.withUserCount ?? false
}`,
);
return bot.transformers.scheduledEvent(bot, event);

View File

@@ -23,14 +23,21 @@ export async function getScheduledEventUsers(
): Promise<
Collection<bigint, User> | Collection<bigint, { user: User; member: Member }>
> {
let url = bot.constants.endpoints.GUILD_SCHEDULED_EVENT_USERS(guildId, eventId)
if (options) {
url = "?"
if (options.limit) url += `limit=${options.limit}`;
if (options.withMember) url += `&with_member=${options.withMember}`
if (options.after) url += `&after=${options.after}`
if (options.before) url += `&before=${options.before}`
}
const result = await bot.rest.runMethod<{ user: DiscordUser; member?: DiscordMember }[]>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_SCHEDULED_EVENT_USERS(guildId, eventId),
{
limit: options?.limit,
with_members: options?.withMember,
},
url
);
if (!options?.withMember) {
@@ -59,6 +66,6 @@ export interface GetScheduledEventUsers {
withMember?: boolean;
/** consider only users before given user id */
before?: bigint;
/** consider only users after given user id */
/** consider only users after given user id. If both before and after are provided, only before is respected. Fetching users in-between before and after is not supported. */
after?: bigint;
}

View File

@@ -8,10 +8,7 @@ export async function getScheduledEvents(bot: Bot, guildId: bigint, options?: Ge
const events = await bot.rest.runMethod<DiscordScheduledEvent[]>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_SCHEDULED_EVENTS(guildId),
{
with_user_count: options?.withUserCount,
},
`${bot.constants.endpoints.GUILD_SCHEDULED_EVENTS(guildId)}?with_user_count=${options?.withUserCount ?? false}`,
);
return new Collection<bigint, ScheduledEvent>(

View File

@@ -3,15 +3,19 @@ import { DiscordInviteMetadata } from "../../types/discord.ts";
/** Returns an invite for the given code or throws an error if the invite doesn't exists. */
export async function getInvite(bot: Bot, inviteCode: string, options?: GetInvite) {
let url = bot.constants.endpoints.INVITE(inviteCode);
if (options) {
url += "?";
if (options.withCounts) url += `with_counts=${options.withCounts}`;
if (options.withExpiration) url += `&with_expiration=${options.withExpiration}`;
if (options.scheduledEventId) url += `&guild_scheduled_event_id=${options.scheduledEventId}`;
}
const result = await bot.rest.runMethod<DiscordInviteMetadata>(
bot.rest,
"get",
bot.constants.endpoints.INVITE(inviteCode),
{
with_counts: options?.withCounts || false,
with_expiration: options?.withExpiration || false,
guild_scheduled_event_id: options?.scheduledEventId?.toString(),
},
url,
);
return {

View File

@@ -8,13 +8,14 @@ import { Collection } from "../../util/collection.ts";
* GW(fetchMembers): 120/m(PER shard) rate limit. Meaning if you have 8 shards your limit is 960/m.
*/
export async function getMembers(bot: Bot, guildId: bigint, options: ListGuildMembers) {
let url = `${bot.constants.endpoints.GUILD_MEMBERS(guildId)}?limit=${options.limit || 1000}`;
if (options.after) url += `&after=${options.after}`;
const result = await bot.rest.runMethod<DiscordMemberWithUser[]>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_MEMBERS(guildId),
{
limit: 1000,
},
url,
);
return new Collection(

View File

@@ -20,14 +20,14 @@ export async function searchMembers(
}
}
let url = `${bot.constants.endpoints.GUILD_MEMBERS_SEARCH(guildId)}?query=${query}`;
if (options?.limit) url += `&limit=${options?.limit}`;
const result = await bot.rest.runMethod<DiscordMemberWithUser[]>(
bot.rest,
"get",
bot.constants.endpoints.GUILD_MEMBERS_SEARCH(guildId),
{
...options,
query,
},
url,
);
return new Collection(

View File

@@ -5,23 +5,26 @@ import { DiscordMessage } from "../../types/discord.ts";
export async function getMessages(
bot: Bot,
channelId: bigint,
options?: GetMessagesAfter | GetMessagesBefore | GetMessagesAround | GetMessagesLimit,
options?: GetMessagesOptions,
) {
if (options?.limit && (options.limit < 0 || options.limit > 100)) {
throw new Error(bot.constants.Errors.INVALID_GET_MESSAGES_LIMIT);
}
let url = bot.constants.endpoints.CHANNEL_MESSAGES(channelId);
if (options) {
if (bot.utils.hasProperty(options, "around")) options.around = (options.around as bigint).toString();
if (bot.utils.hasProperty(options, "before")) options.before = (options.before as bigint).toString();
if (bot.utils.hasProperty(options, "after")) options.after = (options.after as bigint).toString();
url += "?"
if (isGetMessagesAfter(options) && options.after) url += `after=${options.after}`;
if (isGetMessagesBefore(options) && options.before) url += `&before=${options.before}`;
if (isGetMessagesAround(options) && options.around) url += `&around=${options.around}`;
if (isGetMessagesLimit(options) && options.limit) url += `&limit=${options.limit}`;
}
const result = await bot.rest.runMethod<DiscordMessage[]>(
bot.rest,
"get",
bot.constants.endpoints.CHANNEL_MESSAGES(channelId),
options,
url
);
return await Promise.all(result.map((res) => bot.transformers.message(bot, res)));
@@ -50,3 +53,21 @@ export interface GetMessagesAfter extends GetMessagesLimit {
/** Get messages after this message id */
after?: bigint;
}
export type GetMessagesOptions = GetMessagesAfter | GetMessagesBefore | GetMessagesAround | GetMessagesLimit;
export function isGetMessagesAfter(options: GetMessagesOptions): options is GetMessagesAfter {
return Reflect.has(options, "after");
}
export function isGetMessagesBefore(options: GetMessagesOptions): options is GetMessagesBefore {
return Reflect.has(options, "before");
}
export function isGetMessagesAround(options: GetMessagesOptions): options is GetMessagesAround {
return Reflect.has(options, "around");
}
export function isGetMessagesLimit(options: GetMessagesOptions): options is GetMessagesLimit {
return Reflect.has(options, "limit");
}

View File

@@ -16,11 +16,19 @@ export async function getReactions(
reaction = reaction.substring(3, reaction.length - 1);
}
let url = bot.constants.endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, encodeURIComponent(reaction));
if (options) {
url += "?";
if (options.after) url += `after=${options.after}`;
if (options.limit) url += `&limit=${options.limit}`;
}
const users = await bot.rest.runMethod<DiscordUser[]>(
bot.rest,
"get",
bot.constants.endpoints.CHANNEL_MESSAGE_REACTION(channelId, messageId, encodeURIComponent(reaction)),
options,
url,
);
return new Collection(users.map((u) => {

View File

@@ -41,29 +41,12 @@ export function processQueue(rest: RestManager, id: string) {
if (bucketResetIn) continue;
// EXECUTE THE REQUEST
// IF THIS IS A GET REQUEST, CHANGE THE BODY TO QUERY PARAMETERS
const query = queuedRequest.request.method.toUpperCase() === "GET" && queuedRequest.payload.body
? Object.keys(queuedRequest.payload.body)
.filter((key) => (queuedRequest.payload.body as Record<string, string>)[key] !== undefined)
.map(
(key) =>
`${encodeURIComponent(key)}=${
encodeURIComponent(
(queuedRequest.payload.body as Record<string, string>)[key],
)
}`,
)
.join("&")
: "";
const urlToUse = queuedRequest.request.method.toUpperCase() === "GET" && query
? `${queuedRequest.request.url}?${query}`
: queuedRequest.request.url;
// CUSTOM HANDLER FOR USER TO LOG OR WHATEVER WHENEVER A FETCH IS MADE
rest.debug(`[REST - Add To Global Queue] ${JSON.stringify(queuedRequest.payload)}`);
rest.globalQueue.push({
...queuedRequest,
urlToUse: queuedRequest.request.url,
basicURL,
urlToUse,
});
rest.processGlobalQueue(rest);
queue.requests.shift();

View File

@@ -1,6 +1,17 @@
import { RestManager } from "../bot.ts";
import { API_VERSION, BASE_URL, IMAGE_BASE_URL } from "../util/constants.ts";
export async function runMethod<T = any>(
rest: RestManager,
method: "get",
url: string,
): Promise<T>;
export async function runMethod<T = any>(
rest: RestManager,
method: "post" | "put" | "delete" | "patch",
url: string,
body?: unknown,
): Promise<T>;
export async function runMethod<T = any>(
rest: RestManager,
method: "get" | "post" | "put" | "delete" | "patch",