const fs = require('fs') const path = require('path') const Method = require('./method') const logger = require('./logger')() // Reads all scripts in the `scripts` folder, sends to `Method` class to get all methods in the class, and send output to `app.js` class Controller { constructor() { this.main = new Promise((res, rej) => { if (fs.existsSync('./scripts/')) { fs.readdir('./scripts/', (err, files) => { if (err) { logger.Error(`${err.code}: Failed to read directory`) rej(`${err.code}: Failed to read directory`) } this.require = new Map() files.forEach(file => { try { this.require.set(file.replace('.js', ''), require(`../scripts/${file}`)()) } catch (err) { logger.Error(`${err.code}: Failed to read ${file}`) rej(`${err.code}: Failed to read ${file}`) } }) res(this.require) }) } else { fs.mkdirSync('./scripts/') fs.writeFile(path.join('./scripts/', 'index.js'), fs.readFileSync('./examples/index.js', 'utf-8'), (err) => { if (err) { logger.Error(`${err.code}: Error writing to file`) rej(`${err.code}: Error writing to file`) } }) } }).then(output => { return new Promise((res, rej) => { const map = output const object = { map: output, index: map.get('index'), return: new Map() } if (object.index) { object.map.forEach((value, key) => { object.return.set(key, this.#GetMethods(value)) }) } else { logger.Error(`ERROR: 'index.js' does not exist`) rej(`ERROR: 'index.js' does not exist`) } res(object.return) }) }) } async Main(x) { return new Promise((res, rej) => { this.#LoadModules(x).then(output => { if (output) { res(output) } else { logger.Error('ERROR: Unable to load modules') rej('ERROR: Unable to load modules') } }) }) } #GetMethods(x) {return Method().GetMethods(x)} async #LoadModules(x) { return new Promise((res, rej) => { this.main.then(output => { if (output.get('index')) { this.methods = new Map() output.forEach((value, key) => { this.key = key if (this.key === 'index') { this.methods.set('/', value.get('Main')()) } else { value.forEach((value, key) => { if (key === 'Main') { this.methods.set('/' + this.key.toLowerCase(), value(x)) } else { this.methods.set('/' + this.key.toLowerCase() + '/' + key.toLowerCase(), value(x)) } }) } }) if (this.methods !== undefined) { res(this.methods) } else { logger.Error(`Error: Failed to get methods`) rej(`Error: Failed to get methods`) } } else { logger.Error(`Error: 'index.js does not exist'`) rej(`Error: 'index.js' does not exist`) } }) }) } } module.exports = Controller