command.js 1.2 KB

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