proxy-factory.js 1.12 KB
Newer Older
YazhouChen's avatar
YazhouChen committed
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
import { CLOSE_CODES } from '../constants';
import { closeWebSocketConnection } from '../algorithms/close';
import normalizeSendData from './normalize-send';
import { createMessageEvent } from '../event/factory';

export default function proxyFactory(target) {
  const handler = {
    get(obj, prop) {
      if (prop === 'close') {
        return function close(options = {}) {
          const code = options.code || CLOSE_CODES.CLOSE_NORMAL;
          const reason = options.reason || '';

          closeWebSocketConnection(target, code, reason);
        };
      }

      if (prop === 'send') {
        return function send(data) {
          data = normalizeSendData(data);

          target.dispatchEvent(
            createMessageEvent({
              type: 'message',
              data,
              origin: this.url,
              target
            })
          );
        };
      }

      if (prop === 'on') {
        return function onWrapper(type, cb) {
          target.addEventListener(`server::${type}`, cb);
        };
      }

      return obj[prop];
    }
  };

  const proxy = new Proxy(target, handler);
  return proxy;
}