Skip to content

Commit dff96a2

Browse files
committed
Cache commands to determine syncing on start
1 parent b47a7e3 commit dff96a2

File tree

3 files changed

+34
-5
lines changed

3 files changed

+34
-5
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ logs/
1313
!.vscode/extensions.json
1414
.env
1515
dist/
16+
.command_cache.json

src/index.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { SlashCreator, FastifyServer } from 'slash-create';
22
import path from 'path';
33
import dotenv from 'dotenv';
44
import { loadExtractors } from './media';
5+
import { cacheCommands } from './util';
56

67
let dotenvPath = path.join(process.cwd(), '.env');
78
if (path.parse(process.cwd()).name === 'dist') dotenvPath = path.join(process.cwd(), '..', '.env');
@@ -34,11 +35,12 @@ creator
3435
start()
3536
.then(() => loadExtractors())
3637
.then(() => {
37-
creator
38-
.withServer(new FastifyServer())
39-
.registerCommandsIn(path.join(__dirname, 'commands'))
40-
.syncCommands()
41-
.startServer();
38+
creator.withServer(new FastifyServer()).registerCommandsIn(path.join(__dirname, 'commands'));
39+
40+
if (cacheCommands(creator)) {
41+
logger.info('Cache updated, syncing...');
42+
creator.syncCommands();
43+
}
4244

4345
if (process.env.TEST_GUILD) {
4446
const alreadySynced = !!creator.commands.find(
@@ -51,6 +53,8 @@ start()
5153
.then(() => logger.info(`Synced test guild!`))
5254
.catch((e) => logger.error(`Failed to sync test guild!`, e));
5355
}
56+
57+
creator.startServer();
5458
});
5559

5660
// This should serve in localhost:8020/interactions

src/util.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as path from 'path';
22
import * as fs from 'fs';
3+
import { SlashCreator } from 'slash-create';
34

45
/**
56
* Iterates through a folder and calls back on every .js found.
@@ -38,3 +39,26 @@ export async function iterateFolder(
3839
export function randint(min: number, max: number) {
3940
return Math.floor(Math.random() * (max - min + 1)) + min;
4041
}
42+
43+
/**
44+
* Caches commands to a file.
45+
* @param creator The creator to cache commands from
46+
* @returns Whether the cache has updated
47+
*/
48+
export function cacheCommands(creator: SlashCreator) {
49+
let cache = '';
50+
51+
if (fs.existsSync('../.command_cache.json')) cache = fs.readFileSync('../.command_cache.json', { encoding: 'utf-8' });
52+
53+
const currentCache = JSON.stringify(
54+
creator.commands.map((cmd) => ({
55+
...cmd.commandJSON,
56+
guildIDs: cmd.guildIDs
57+
}))
58+
);
59+
60+
if (cache === currentCache) return false;
61+
62+
fs.writeFileSync('../.command_cache.json', currentCache);
63+
return true;
64+
}

0 commit comments

Comments
 (0)