12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- const express = require('express');
- const router = express.Router();
- var path = require('path');
- const Logger = require('./LoggerSystem');
- class ActionSystem {
- constructor() {
- this.events = {};
- }
- on(eventName, fn, post = false) {
- if(!eventName) {
- Logger.error(`ActionSystem Error: Cannot add event with name '${eventName}'`)
- }
- if(!fn || typeof fn !== "function") {
- Logger.error(`ActionSystem Error: Cannot add empty function`);
- }
- if(post) {
- eventName += "POST";
- }
- if(!this.events[eventName])
- this.events[eventName] = [];
- this.events[eventName].push(fn);
- }
- clear(eventName) {
- delete this.events[eventName];
- }
- emitSync(eventName, data, req, res) {
- if(!this.events[eventName] && !this.events[eventName+"POST"]) return data;
- return [...(this.events[eventName]||[]), ...(this.events[eventName+"POST"]||[])].reduce((initial, fn) => fn(initial, req, res), data);
- }
-
- emit(eventName, data, req, res) {
- if(!this.events[eventName] && !this.events[eventName+"POST"]) return Promise.resolve(data);
- console.log(this.events[eventName])
- console.log(this.events[eventName+"POST"])
- return [...(this.events[eventName]||[]), ...(this.events[eventName+"POST"]||[])].reduce((initial, fn) =>
- initial.then(result => fn(result, req, res))
- , Promise.resolve(data))
- }
- emitArray(eventName, arr, req, res) {
- if(!arr || !arr.length) return Promise.resolve(arr);
- return Promise.all(arr.map((item) => this.emit('Array'+eventName, item, req, res))
- .map((p) => p.catch(() => undefined)))
- .then((res) => {
- let nres = [];
- for(var i in res) {
- if(res[i])nres.push(res[i])
- }
- return nres;
- });
- }
- debug() {
- console.log("[!]The following events are added to the ActionSystem:")
- for(var i in this.events) {
- console.log(`EventName: ${i} \t Callbacks: ${this.events[i].length}`);
- }
- console.log("[--------------------------------------------------------------]")
- }
- }
- module.exports = new ActionSystem();
|