command.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const EventEmitter = require('events').EventEmitter;
  3. class Command extends EventEmitter {
  4. constructor() {
  5. super();
  6. this.next = null;
  7. }
  8. // slow. debug only
  9. stateName() {
  10. const state = this.next;
  11. for (const i in this) {
  12. if (this[i] === state && i !== 'next') {
  13. return i;
  14. }
  15. }
  16. return 'unknown name';
  17. }
  18. execute(packet, connection) {
  19. if (!this.next) {
  20. this.next = this.start;
  21. connection._resetSequenceId();
  22. }
  23. if (packet && packet.isError()) {
  24. const err = packet.asError(connection.clientEncoding);
  25. if (this.onResult) {
  26. this.onResult(err);
  27. this.emit('end');
  28. } else {
  29. this.emit('error', err);
  30. this.emit('end');
  31. }
  32. return true;
  33. }
  34. // TODO: don't return anything from execute, it's ugly and error-prone. Listen for 'end' event in connection
  35. this.next = this.next(packet, connection);
  36. if (this.next) {
  37. return false;
  38. }
  39. this.emit('end');
  40. return true;
  41. }
  42. }
  43. module.exports = Command;