Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit ae15f37

Browse files
committed
Use fs async
1 parent e8ab141 commit ae15f37

File tree

4 files changed

+30
-23
lines changed

4 files changed

+30
-23
lines changed

src/Kirin/classes/APIClient.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { RequestHandler, RequestHandlerOptions } from './RequestHandler.js';
2-
import { existsSync, lstatSync, mkdirSync, readdirSync } from 'fs';
32
import express, { Express, Request, Response } from 'express';
43
import { SocketEvents } from '../types/SocketEvents.js';
54
import { Server as SocketServer } from 'socket.io';
@@ -10,8 +9,10 @@ import { Logger } from 'fallout-utility';
109
import { Kirin } from '../../Kirin.js';
1110
import bodyParser from 'body-parser';
1211
import { fileURLToPath } from 'url';
12+
import { existsSync } from 'fs';
1313
import path from 'path';
1414
import cors from 'cors';
15+
import { mkdir, readdir, stat } from 'fs/promises';
1516

1617
export class APIClient<Ready extends boolean = boolean> {
1718
private _express: Express = express();
@@ -66,9 +67,9 @@ export class APIClient<Ready extends boolean = boolean> {
6667
}
6768

6869
public async loadRoutes(): Promise<void> {
69-
if (!existsSync(this.routesDir)) mkdirSync(this.routesDir);
70+
if (!existsSync(this.routesDir)) await mkdir(this.routesDir);
7071

71-
const files = readdirSync(this.routesDir).map(f => path.join(this.routesDir, f)).filter(f => f.endsWith('.js') && lstatSync(f).isFile());
72+
const files = await Promise.all((await readdir(this.routesDir)).map(f => path.join(this.routesDir, f)).filter(async f => f.endsWith('.js') && (await stat(f)).isFile()));
7273

7374
for (const file of files) {
7475
try {

src/Kirin/classes/Server.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { APIButtonComponentBase, BaseMessageOptions, ButtonBuilder, ButtonStyle, ChannelType, ComponentType, Guild, GuildTextBasedChannel, If, Message, PermissionResolvable, PermissionsBitField, StageChannel, inlineCode, mergeDefault } from 'discord.js';
22
import { Logger, recursiveObjectReplaceValues, PartialDeep } from 'fallout-utility';
33
import { resolveFromCachedManager } from '../utils/managers.js';
4-
import { readFileSync, rmSync, writeFileSync } from 'fs';
54
import { PingData, pingServer } from '../utils/ping.js';
65
import { ChildProcess, spawn } from 'child_process';
76
import { ServerManager } from './ServerManager.js';
87
import { Kirin } from '../../Kirin.js';
98
import { randomBytes } from 'crypto';
109
import { cli } from 'reciple';
1110
import path from 'path';
11+
import { readFile, rm, writeFile } from 'fs/promises';
1212

1313
export type ServerDataWithIdStatus = ServerData & { id: string; status: ServerStatus; };
1414

@@ -156,7 +156,6 @@ export class Server<Ready extends boolean = boolean> {
156156
detached: !this.server.killOnBotStop,
157157
killSignal: this.server.killSignal || 'SIGINT',
158158
env: process.env,
159-
// shell: true,
160159
stdio: []
161160
});
162161

@@ -256,7 +255,7 @@ export class Server<Ready extends boolean = boolean> {
256255

257256
this._deleted = true;
258257

259-
if (deleteJsonFile && this.file) rmSync(this.file, { force: true, recursive: true });
258+
if (deleteJsonFile && this.file) await rm(this.file, { force: true, recursive: true });
260259
}
261260

262261
public async update(options: PartialDeep<ServerData>): Promise<this> {
@@ -279,7 +278,7 @@ export class Server<Ready extends boolean = boolean> {
279278
if (isFetch) await this.fetch();
280279
if (!oldOptions.messageId && newOptions.messageId && this.channel) await this.createMessage({ deleteOld: true });
281280

282-
this.saveJson();
281+
await this.saveJson();
283282

284283
return this;
285284
}
@@ -302,7 +301,7 @@ export class Server<Ready extends boolean = boolean> {
302301
this.options.channelId = channel?.id;
303302
}
304303

305-
this.saveJson();
304+
await this.saveJson();
306305
}
307306

308307
public async ping(): Promise<PingData> {
@@ -321,12 +320,12 @@ export class Server<Ready extends boolean = boolean> {
321320
return newPing;
322321
}
323322

324-
public saveJson(file?: string | null): void {
323+
public async saveJson(file?: string | null): Promise<void> {
325324
file = file ?? this.file;
326325
if (!file) throw new Error('No file path specified');
327326
if (!this.file) this.options.file = file;
328327

329-
writeFileSync(file, JSON.stringify(this.toJSON(true), null, 2));
328+
await writeFile(file, JSON.stringify(this.toJSON(true), null, 2));
330329
}
331330

332331
public isFetched(): this is Server<true> {
@@ -381,7 +380,7 @@ export class Server<Ready extends boolean = boolean> {
381380
if (cached) return cached;
382381
}
383382

384-
const serverJson: ServerData = JSON.parse(readFileSync(file, 'utf-8'));
383+
const serverJson: ServerData = JSON.parse(await readFile(file, 'utf-8'));
385384
const server: Server = new Server(serverJson, kirin);
386385

387386
serverJson.file = file;

src/Kirin/routes/create.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { Server, ServerData } from '../classes/Server.js';
2-
import { mkdirSync, rmSync, writeFileSync } from 'fs';
32
import { APIClient } from '../classes/APIClient.js';
43
import crypto from 'crypto';
54
import path from 'path';
5+
import { mkdir, rm, writeFile } from 'fs/promises';
66

77
export default (api: APIClient) => {
88
const apiPath = api.apiPath + '/servers';
@@ -17,13 +17,13 @@ export default (api: APIClient) => {
1717

1818
const file = path.join(api.kirin.serversDir, crypto.randomBytes(10).toString('base64url') + '.json');
1919

20-
mkdirSync(api.kirin.serversDir, { recursive: true });
21-
writeFileSync(file, JSON.stringify(data, null, 2));
20+
await mkdir(api.kirin.serversDir, { recursive: true });
21+
await writeFile(file, JSON.stringify(data, null, 2));
2222

2323
const server = await Server.from(file, api.kirin, true).catch(() => null);
2424

2525
if (!server) {
26-
rmSync(file, { force: true });
26+
await rm(file, { force: true });
2727
return requestHandler.sendAPIErrorResponse(400, { error: 'ServerCreateFailed', message: 'Unable to resolve server data' });
2828
}
2929

src/KirinAdmin.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import { APIModalInteractionResponseCallbackData, ButtonStyle, ChatInputCommandInteraction, ComponentType, EmbedBuilder, Message, TextInputBuilder, TextInputStyle } from 'discord.js';
1+
import { APIModalInteractionResponseCallbackData, ButtonStyle, ChatInputCommandInteraction, ComponentType, EmbedBuilder, Message, TextInputBuilder, TextInputStyle, codeBlock } from 'discord.js';
22
import { AnyCommandBuilder, AnyCommandData, RecipleClient, RecipleModuleScript, SlashCommandBuilder, cli } from 'reciple';
33
import { recursiveObjectReplaceValues } from 'fallout-utility';
44
import { Server, ServerData } from './Kirin/classes/Server.js';
55
import { serverOption } from './Kirin/utils/commandOption.js';
66
import { commandHalt } from './Kirin/utils/commandHalt.js';
7-
import { mkdirSync, rmSync, writeFileSync } from 'fs';
87
import kirin, { Kirin } from './Kirin.js';
98
import { randomBytes } from 'crypto';
109
import path from 'path';
10+
import { mkdir, rm, writeFile } from 'fs/promises';
1111

1212
export class KirinAdmin implements RecipleModuleScript {
1313
readonly versions: string = '^7';
@@ -155,8 +155,8 @@ export class KirinAdmin implements RecipleModuleScript {
155155
command: 'java',
156156
cwd: modalInteraction.fields.getTextInputValue('cwd'),
157157
jar: modalInteraction.fields.getTextInputValue('jar'),
158-
args: modalInteraction.fields.getTextInputValue('args').split(/(\s+)/).filter(Boolean),
159-
serverArgs: modalInteraction.fields.getTextInputValue('serverArgs').split(/(\s+)/).filter(Boolean),
158+
args: modalInteraction.fields.getTextInputValue('args').split(/(\s+)/).filter(v => v.trim()),
159+
serverArgs: modalInteraction.fields.getTextInputValue('serverArgs').split(/(\s+)/).filter(v => v.trim()),
160160
killOnBotStop: false,
161161
killSignal: 'SIGINT'
162162
},
@@ -201,14 +201,21 @@ export class KirinAdmin implements RecipleModuleScript {
201201

202202
const file = path.join(this.kirin.serversDir, randomBytes(10).toString('base64url') + '.json');
203203

204-
mkdirSync(this.kirin.serversDir, { recursive: true });
205-
writeFileSync(file, JSON.stringify(serverData, null, 2));
204+
await mkdir(this.kirin.serversDir, { recursive: true });
205+
await writeFile(file, JSON.stringify(serverData, null, 2));
206206

207-
const server = await Server.from(file, this.kirin, true).catch(() => null);
207+
let err: any;
208+
209+
const server = await Server.from(file, this.kirin, true).catch(error => {
210+
err = error;
211+
});
208212

209213
if (!server) {
214+
this.kirin.logger?.err(err);
215+
await interaction.editReply(`An error occured while creating server!\n${codeBlock(String(err))}`);
210216
await message?.delete().catch(() => {});
211-
rmSync(file, { force: true });
217+
await rm(file, { force: true });
218+
return;
212219
}
213220

214221
await modalInteraction.editReply('Server created!');

0 commit comments

Comments
 (0)