base.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import {Command, Session} from "../session";
  2. export interface CommandHandler {
  3. accept_command: string[],
  4. handle_message(msg: Command): void
  5. }
  6. export class CloseHandler implements CommandHandler {
  7. accept_command: string[] = ['close_session'];
  8. constructor(readonly session: Session) {
  9. }
  10. handle_message(msg: Command) {
  11. this.session.close_session();
  12. }
  13. }
  14. export class CommandDispatcher {
  15. command2handler: { [cmd: string]: CommandHandler } = {};
  16. constructor(...handlers: CommandHandler[]) {
  17. for (let h of handlers) {
  18. for (let cmd of h.accept_command) {
  19. if (cmd in this.command2handler)
  20. throw new Error(`Conflict command handler: both ${this.command2handler[cmd]} and ${h} accepts '${cmd}' command`);
  21. this.command2handler[cmd] = h;
  22. }
  23. }
  24. }
  25. dispatch_message(msg: Command): boolean {
  26. if (msg.command in this.command2handler) {
  27. this.command2handler[msg.command].handle_message(msg);
  28. return true;
  29. }
  30. return false
  31. }
  32. }