throw API errors

This commit is contained in:
Shay
2022-04-08 14:48:43 -07:00
parent 2705a61be4
commit 27c30b1e0c
2 changed files with 15 additions and 5 deletions

View File

@@ -15,17 +15,19 @@ async function HasGuildCommand(appId, guildId, command) {
try {
const res = await DiscordRequest(endpoint, { method: 'GET' });
const data = await res.json();
if (data) {
const installedNames = data.map((c) => c['name']);
// This is just matching on the name, so it's not good for updates
if (!installedNames.includes(command['name'])) {
console.log(`Installing "${command['name']}"`);
InstallGuildCommand(appId, guildId, command);
} else {
console.log(`"${command['name']}" command already installed`);
}
}
} catch (err) {
console.error('Error installing commands: ', err);
console.error(err);
}
}
@@ -37,7 +39,7 @@ export async function InstallGuildCommand(appId, guildId, command) {
try {
await DiscordRequest(endpoint, { method: 'POST', body: command });
} catch (err) {
console.error('Error installing commands: ', err);
console.error(err);
}
}

View File

@@ -15,19 +15,27 @@ export function VerifyDiscordRequest(clientKey) {
};
}
export function DiscordRequest(endpoint, options) {
export async function DiscordRequest(endpoint, options) {
// append endpoint to root API URL
const url = 'https://discord.com/api/v9/' + endpoint;
// Stringify payloads
if (options.body) options.body = JSON.stringify(options.body);
// Use node-fetch to make requests
return fetch(url, {
headers: {
const res = await fetch(url, {
headers: {
Authorization: `Bot ${process.env.DISCORD_TOKEN}`,
'Content-Type': 'application/json; charset=UTF-8',
},
...options
});
// throw API errors
if (!res.ok) {
const data = await res.json();
console.log(res.status);
throw new Error(JSON.stringify(data));
}
// return original response
return res;
}
// Simple method that returns a random emoji from list