ActionSystem.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const express = require('express');
  2. const router = express.Router();
  3. var path = require('path');
  4. const Logger = require('./LoggerSystem');
  5. class ActionSystem {
  6. constructor() {
  7. this.events = {};
  8. }
  9. on(eventName, fn, post = false) {
  10. if(!eventName) {
  11. Logger.error(`ActionSystem Error: Cannot add event with name '${eventName}'`)
  12. }
  13. if(!fn || typeof fn !== "function") {
  14. Logger.error(`ActionSystem Error: Cannot add empty function`);
  15. }
  16. if(post) {
  17. eventName += "POST";
  18. }
  19. if(!this.events[eventName])
  20. this.events[eventName] = [];
  21. this.events[eventName].push(fn);
  22. }
  23. clear(eventName) {
  24. delete this.events[eventName];
  25. }
  26. emitSync(eventName, data, req, res) {
  27. if(!this.events[eventName] && !this.events[eventName+"POST"]) return data;
  28. return [...(this.events[eventName]||[]), ...(this.events[eventName+"POST"]||[])].reduce((initial, fn) => fn(initial, req, res), data);
  29. }
  30. emit(eventName, data, req, res) {
  31. if(!this.events[eventName] && !this.events[eventName+"POST"]) return Promise.resolve(data);
  32. console.log(this.events[eventName])
  33. console.log(this.events[eventName+"POST"])
  34. return [...(this.events[eventName]||[]), ...(this.events[eventName+"POST"]||[])].reduce((initial, fn) =>
  35. initial.then(result => fn(result, req, res))
  36. , Promise.resolve(data))
  37. }
  38. emitArray(eventName, arr, req, res) {
  39. if(!arr || !arr.length) return Promise.resolve(arr);
  40. return Promise.all(arr.map((item) => this.emit('Array'+eventName, item, req, res))
  41. .map((p) => p.catch(() => undefined)))
  42. .then((res) => {
  43. let nres = [];
  44. for(var i in res) {
  45. if(res[i])nres.push(res[i])
  46. }
  47. return nres;
  48. });
  49. }
  50. debug() {
  51. console.log("[!]The following events are added to the ActionSystem:")
  52. for(var i in this.events) {
  53. console.log(`EventName: ${i} \t Callbacks: ${this.events[i].length}`);
  54. }
  55. console.log("[--------------------------------------------------------------]")
  56. }
  57. }
  58. module.exports = new ActionSystem();