All files / src client.ts

96.55% Statements 28/29
100% Branches 10/10
85.71% Functions 6/7
96.42% Lines 27/28

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 64 65 66 67 68 69 70 71 72 73  1x   1x 1x   1x   1x 80x 80x 236x   80x 79x         80x 80x 80x 82x                   82x     18x 18x     64x   64x       82x 82x   80x         80x           80x 5x       5x       75x        
import * as net from "net";
import { Logger } from "./logger";
 
const Parser = require("redis-parser");
const logger: Logger = new Logger(module.id);
 
let previousListener: any = null;
 
export const sendCommand = (client: net.Socket, commands: string[]): Promise<string | string[] | null> => {
    let commandString = `*${commands.length}\r\n`;
    for (const element of commands) {
        commandString += `$${element.length}\r\n${element}\r\n`;
    }
    if (previousListener) {
        client.removeListener(
            "data",
            previousListener
        );
    }
    return new Promise((resolve) => {
        let response: string | null = null;
        previousListener = (data: any) => {
            logger.debug(`client REPLY: ${data.toString().
                replace(
                    /\r/g,
                    "\\r"
                ).
                replace(
                    /\n/g,
                    "\\n"
                )}`);
 
            const parser = new Parser({
                "returnBuffers": false,
                "returnError": (err: any) => {
                    response = err.toString();
                    resolve(response);
                },
                "returnReply": (reply: any) => {
                    response = reply;
                    //          TODO: client.destroy();
                    resolve(response);
                },
                "stringNumbers": false
            });
            parser.reset();
            parser.execute(data);
        };
        client.on(
            "data",
            previousListener
        );
 
        client.on(
            "close",
            (hadError: boolean) => {
                logger.debug(`client.close() ERROR: ${hadError}`);
            }
        );
        if (client.remoteAddress === undefined && client.remotePort === undefined) {
            client.connect(
                Number(process.env.REDIS_PORT || 6379),
                process.env.REDIS_HOST || "localhost",
                () => {
                    client.write(commandString);
                }
            );
        } else {
            client.write(commandString);
        }
    });
};