E.W.O. Next / All files / src/engine/Commands/tasks runCommands.ts

24.32% Statements 9/37
0% Branches 0/14
0% Functions 0/8
24.32% Lines 9/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80          3x   3x 3x 3x 3x   3x     3x     3x                                                                               3x                                          
/**
 * @module Engine.Commands.Tasks
 * Command runner
 */
 
import { SaveDBCommand } from '@commands/index';
import { Command } from '@engine/Commands/Command';
import { store } from '@engine/store';
import * as async from 'async';
import { List } from 'immutable';
import { addLazyCommand } from '../CommandsTools';
 
export class RunCommands {
 
  public static queueCommand: async.AsyncQueue<Command>;
  public static lazyCommands: List<Command> = List();
  public static timerTenMinute: NodeJS.Timeout | number;
 
  public static startAutoSave = () => {
 
    RunCommands.timerTenMinute = setInterval(
      () => {
        addLazyCommand(new SaveDBCommand());
      },
      10 * 60 * 1000);
  }
 
  public static makeQueues() {
    if (RunCommands.instance === null) {
      RunCommands.instance = new RunCommands();
    }
    return RunCommands.instance;
  }
 
  public static resolveCommand(current: Command, callback?: () => void) {
    console.log(`starting task ${current.command}`);
    const test = current.eligible(current.payload, store);
    const meta = typeof test === 'boolean' ? current.payload : { ...test.meta, ...current.payload };
    const eligible = typeof test === 'boolean' ? test : test.result;
    console.log({ test, meta, eligible });
    if (eligible) {
      const actions = current.execute(meta, store);
      actions.forEach(action => {
        store.dispatch(action);
      });
    }
 
    if (callback) {
      callback();
    }
 
    if (current.callback) {
      current.callback();
    }
 
    console.log(`ending task ${current.command}`);
  }
 
  private static instance: RunCommands = null;
 
  private constructor() {
 
    RunCommands.queueCommand = async.queue(
      (current: Command, callback) => {
        RunCommands.resolveCommand(current, callback);
      },
      1);
 
    (RunCommands.queueCommand.drain as any)(() => {
      console.log('the queue is completed');
      if (RunCommands.lazyCommands.size > 0) {
        console.log('executing lazy commands');
        const commands = RunCommands.lazyCommands.toArray();
        RunCommands.lazyCommands = List();
        RunCommands.queueCommand.push(commands);
      }
    });
  }
}