This commit is contained in:
Flummi 2019-08-20 18:51:55 +00:00
parent cc58237696
commit b6d3212828

View File

@ -1,9 +1,8 @@
import _fs from "fs"; import fs from "fs";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { dirname } from "path"; import { dirname } from "path";
import EventEmitter from "events"; import EventEmitter from "events";
const fs = _fs.promises;
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
export default class cuffeo extends EventEmitter { export default class cuffeo extends EventEmitter {
@ -13,34 +12,29 @@ export default class cuffeo extends EventEmitter {
this.libs = {}; this.libs = {};
return (async () => { return (async () => {
await this.loadLibs(); this.libs = await this.loadLibs();
this.clients = await this.init(cfg); this.clients = this.registerClients(cfg);
return this; return this;
})(); })();
} }
async loadLibs() { async loadLibs() {
const _clients = (await fs.readdir(`${__dirname}/clients`)).filter(f => f.endsWith(".mjs")); const _libs = {};
for(const client of _clients) { for (const client of (await fs.promises.readdir(`${__dirname}/clients`)).filter(f => f.endsWith(".mjs"))) {
const lib = await import(`./clients/${client}`); const lib = await import(`./clients/${client}`);
this.libs[lib.default.name] = lib.default; _libs[lib.default.name] = lib.default;
} }
return; return _libs;
} }
async init(cfg) { registerClients(cfg) {
const clients = []; return cfg.filter(e => e.enabled).map(srv => {
for (const srv in cfg) { if(!Object.keys(this.libs).includes(srv.type))
if(!cfg[srv].enabled) throw new Error(`not supported client: ${srv.type}`);
return new Error("not enabled");
if(!Object.keys(this.libs).includes(cfg[srv].type))
return new Error("not supported client");
clients.push({ return {
name: cfg[srv].network, name: srv.network,
type: cfg[srv].type, type: srv.type,
client: new this.libs[cfg[srv].type](cfg[srv]) client: new this.libs[srv.type](srv)
}); };
} });
clients.forEach(client => client.client.on("data", e => this.emit(e[0], e[1])));
return clients;
} }
}; };