diff --git a/src/services/APIService.js b/src/services/APIService.js new file mode 100644 index 0000000..5d28d16 --- /dev/null +++ b/src/services/APIService.js @@ -0,0 +1,31 @@ +import path from 'path'; +import fs from 'fs'; +import { pathToFileURL } from 'url'; +import chalk from 'chalk'; + +const APIService = class { + APIs = {}; + + async init() { + const apiPath = path.resolve('src/api'); + const folders = fs.readdirSync(apiPath); + for (const folder of folders) { + const curPath = path.join(apiPath, folder, 'index.js'); + await import(pathToFileURL(curPath).toString()).then(res => { + this.APIs[res.default.name] = res.default.execute; + }); + + } + return this; + } + + get(api) { + if (api in this.APIs) { + return this.APIs[api]; + } else { + console.log(`${chalk.red('Error:')} API method not found`); + } + } +}; + +export default APIService; diff --git a/src/~Luna.js b/src/~Luna.js index 3ba82bb..b8eb508 100644 --- a/src/~Luna.js +++ b/src/~Luna.js @@ -4,6 +4,7 @@ import chalk from 'chalk'; import pjson from '../package.json' assert { type: 'json' }; import InteractionHandler from './handlers/InteractionHandler.js'; import PresenceHandler from './handlers/PresenceHandler.js'; +import APIService from './services/APIService.js'; config(); const TOKEN = process.env.TOKEN; @@ -23,6 +24,7 @@ const LunaInteractionHandler = await new InteractionHandler().init(TOKEN) console.log(`${chalk.red('Error:')} can not initialize InteractionHandler`) throw err; }); +const LunaAPIService = await new APIService().init(); const Luna = new Discord.Client({ allowedMentions: { @@ -105,7 +107,7 @@ Luna.on(Discord.Events.ClientReady, async () => { }); Luna.on(Discord.Events.InteractionCreate, async (interaction) => { - await LunaInteractionHandler.handle(interaction); + await LunaInteractionHandler.handle(interaction, LunaAPIService); }); await Luna.login(TOKEN);