All files / src/resp/command/server unsubscribe-command.ts

33.33% Statements 8/24
0% Branches 0/6
50% Functions 1/2
33.33% Lines 8/24

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 551x   1x 1x                             1x 4x   4x   4x   4x                                                          
import { Logger } from "../../../logger";
import { IRequest } from "../../../server/request";
import { RedisToken } from "../../protocol/redis-token";
import { IRespCommand } from "../resp-command";
 
/**
 * ### Available since 2.0.0.
 * ### UNSUBSCRIBE [channel [channel ...]]
 *
 * Unsubscribes the client from the given channels, or from all of them if none is given.
 *
 * When no channels are specified, the client is unsubscribed from all the previously
 * subscribed channels. In this case, a message for every unsubscribed channel will be sent
 * to the client.
 * ### Return value
 * Appears to be an array.  The 'unsubscribe' keyword followed by the list of subscribed
 * channels and then the count of those channels.
 */
export class UnsubscribeCommand extends IRespCommand {
    public maxParams = -1
 
    public minParams = 1
 
    public name = "unsubscribe"
 
    private logger: Logger = new Logger(module.id);
 
    public execSync(request: IRequest): RedisToken {
        this.logger.debug(
            `${request.getCommand()}.execute(%s)`,
            ...request.getParams()
        );
        const response: RedisToken[] = [RedisToken.string("unsubscribe")],
            channels: string[] = [];
        for (const channel of request.getParams()) {
            if (channels.indexOf(channel) === -1) {
                channels.push(channel);
            }
        }
        if (channels.length === 0) {
            channels.push(...request.getSession().getSubscriptionNames());
        }
        for (const channel of channels) {
            this.logger.debug(`Trying to unsubscribe from channel "${channel}"`);
            response.push(RedisToken.string(channel));
            const timedEvent: any = request.getSession().getSubscription(channel);
            if (timedEvent) {
                request.getSession().unSubscribe(channel);
            }
        }
        response.push(RedisToken.integer(request.getSession().getSubscriptionNames().length));
        return RedisToken.array(response);
    }
}