Grapeoff
@Grapeoff
В чём концепция...?

Как мутировать поля Singleton-Класса?

Имеется вот такой Singleton класс для работы с командами для дискорд бота:

import { Command } from '@common/commands/command';
import * as fs from 'node:fs';
import path from 'node:path';

export class ApplicationCommands {
    private static _instance: ApplicationCommands;

    private _commands: Command[] = [];
    private _areCommandsRegistered = false;

    get commands(): Command[] {
        return ApplicationCommands._instance._commands;
    }

    private constructor() {}

    public static getInstance() {
        if (!ApplicationCommands._instance) {
            ApplicationCommands._instance = new ApplicationCommands();
        }

        return ApplicationCommands._instance;
    }

    public async registerAllApplicationCommands() {
        if (!ApplicationCommands._instance._areCommandsRegistered) {
            const commandsPath = path.join(process.cwd(), 'dist', 'commands');

            fs.readdir(commandsPath, async (err, files) => {
                for (const file of files.filter(file => file.endsWith('.js'))) {
                    const filePath = path.join(commandsPath, file);
                    const command: Command = await import(filePath);

                    ApplicationCommands._instance._commands.push(command);
                    ApplicationCommands._instance._areCommandsRegistered = true;
                }
            });
        }

        return ApplicationCommands._instance;
    }
}

Файлы находятся, в массив попадают, но почему-то когда я обращаюсь к геттеру commands, то получаю пустой массив.

async function initialize() {
    const applicationCommands =
        await ApplicationCommands.getInstance().registerAllApplicationCommands();

    console.log(applicationCommands.commands); // []
}
  • Вопрос задан
  • 39 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы