All files / src/resp/protocol resp-serialize.ts

96.96% Statements 32/33
92.3% Branches 12/13
100% Functions 2/2
96.96% Lines 32/33

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 641x 1x   1x   1x 1x   1x   1x   1x   1x   1x   141x   141x   141x       141x 141x 17x 17x 59x     124x   17x 17x   28x 28x   61x 55x   6x   61x 61x     18x     18x     141x       141x      
import * as util from "util";
import {Logger} from "../../logger";
import {AbstractRedisToken} from "../protocol/abstract-redis-token";
import {RedisTokenType} from "../protocol/redis-token-type";
 
export class RespSerialize {
  private static ARRAY = "*";
 
  private static ERROR = "-";
 
  private static INTEGER = ":";
 
  private static SIMPLE_STRING = "+";
 
  private static BULK_STRING = "$";
 
  private static DELIMITER = "\r\n";
 
  private logger: Logger = new Logger(module.id);
 
  private value: string = "";
 
  constructor(private message: AbstractRedisToken<any>) {
  }
 
  public serialize(): string {
      this.logger.debug(`serialize(${util.inspect(this.message)}) - typeOf = ${this.message.constructor.name}`);
      if (this.message.getType() === RedisTokenType.ARRAY) {
          this.value += `${RespSerialize.ARRAY}${this.message.getValue().length}${RespSerialize.DELIMITER}`;
          for (const obj of this.message.getValue()) {
              this.value += new RespSerialize(obj).serialize();
          }
      } else {
          switch (this.message.getType()) {
          case RedisTokenType.STATUS:
              this.value += `${RespSerialize.SIMPLE_STRING}${this.message.getValue()}${RespSerialize.DELIMITER}`;
              break;
          case RedisTokenType.INTEGER:
              this.value += `${RespSerialize.INTEGER}${this.message.getValue()}${RespSerialize.DELIMITER}`;
              break;
          case RedisTokenType.STRING:
              if (this.message.getValue() && String(this.message.getValue()).length > 0) {
                  this.value += `${RespSerialize.BULK_STRING}${String(this.message.getValue()).length}${RespSerialize.DELIMITER}${this.message.getValue().toString()}`;
              } else {
                  this.value += `${RespSerialize.BULK_STRING}-1`;
              }
              this.value += `${RespSerialize.DELIMITER}`;
              break;
          case RedisTokenType.ERROR:
          default:
              Iif (this.message.getType() !== RedisTokenType.ERROR) {
                  this.logger.warn(`msg.type is unexpected: ${this.message.getType()}`);
              }
              this.value += `${RespSerialize.ERROR}${this.message.getValue()}${RespSerialize.DELIMITER}`;
          }
      }
      this.logger.debug(
          "The serialized value is %s",
          this.value
      );
      return this.value;
  }
}