All files / realtime/polling PacketReceiver.ts

90% Statements 27/30
37.5% Branches 3/8
100% Functions 5/5
89.29% Lines 25/28
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                                12x             12x 5x 5x 5x 5x         5x   12x 3x 3x 3x 3x 3x                     22x 22x 22x 21x 21x 21x 26x 26x 26x       21x             21x     12x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { exceptionGuard } from '../../core/util/util';
 
/**
 * This class ensures the packets from the server arrive in order
 * This class takes data from the server and ensures it gets passed into the callbacks in order.
 * @constructor
 */
export class PacketReceiver {
  pendingResponses: any[] = [];
  currentResponseNum = 0;
  closeAfterResponse = -1;
  onClose: (() => void) | null = null;
 
  /**
   * @param onMessage_
   */
  constructor(private onMessage_: (a: Object) => void) {}
 
  closeAfter(responseNum: number, callback: () => void) {
    this.closeAfterResponse = responseNum;
    this.onClose = callback;
    Eif (this.closeAfterResponse < this.currentResponseNum) {
      this.onClose();
      this.onClose = null;
    }
  }
 
  /**
   * Each message from the server comes with a response number, and an array of data. The responseNumber
   * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
   * browsers will respond in the same order as the requests we sent
   * @param {number} requestNum
   * @param {Array} data
   */
  handleResponse(requestNum: number, data: any[]) {
    this.pendingResponses[requestNum] = data;
    while (this.pendingResponses[this.currentResponseNum]) {
      const toProcess = this.pendingResponses[this.currentResponseNum];
      delete this.pendingResponses[this.currentResponseNum];
      for (let i = 0; i < toProcess.length; ++i) {
        Eif (toProcess[i]) {
          exceptionGuard(() => {
            this.onMessage_(toProcess[i]);
          });
        }
      }
      Iif (this.currentResponseNum === this.closeAfterResponse) {
        if (this.onClose) {
          this.onClose();
          this.onClose = null;
        }
        break;
      }
      this.currentResponseNum++;
    }
  }
}