All files / src/resp/command/set sadd-command.ts

44% Statements 11/25
0% Branches 0/2
50% Functions 1/2
45.83% Lines 11/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 55 56 57 58 59 60 61 62 63 64 65 66 671x   1x   1x 1x 1x                                     1x 4x   4x   4x   4x   4x                                                                
import { Logger } from "../../../logger";
import { IRequest } from "../../../server/request";
import { DataType } from "../../data/data-type";
import { Database } from "../../data/database";
import { DatabaseValue } from "../../data/database-value";
import { RedisToken } from "../../protocol/redis-token";
import { IRespCommand } from "./../resp-command";
 
/**
 * ### Available since 1.0.0.
 * ### SADD key member [member ...]
 * Add the specified members to the set stored at key. Specified members that are already
 * a member of this set are ignored. If key does not exist, a new set is created before
 * adding the specified members.
 *
 * An error is returned when the value stored at key is not a set.
 *
 * ### Return value
 * Integer reply: the number of elements that were added to the set, not including all the
 * elements already present into the set.
 *
 * ### History
 * >= 2.4: Accepts multiple member arguments. Redis versions before 2.4 are only able to add a
 * single member per call. **unit-redis-ness implements the 2.4 version of this command.**
 */
export class SAddCommand extends IRespCommand {
    public DbDataType = DataType.SET
 
    public maxParams = -1
 
    public minParams = 2
 
    public name = "sadd"
 
    private logger: Logger = new Logger(module.id);
 
    public execSync(request: IRequest, db: Database): RedisToken {
        this.logger.debug(
            `${request.getCommand()}.execute(%s)`,
            ...request.getParams()
        );
        const skey: string = request.getParam(0),
            initial: DatabaseValue = db.getOrDefault(
                skey,
                new DatabaseValue(
                    DataType.SET,
                    new Set()
                )
            ),
            originalSet: Set<any> = initial.getSet(),
            initialCount: number = originalSet.size;
        this.logger.debug(`Initial key length of ${skey} is ${initialCount}`);
        for (let index = 1; index < request.getParams().length; index++) {
            const newValue = request.getParam(index);
            if (!originalSet.has(newValue)) {
                originalSet.add(newValue);
            }
        }
        this.logger.debug(`Final key length of ${skey} is ${originalSet.size}`);
        db.put(
            skey,
            DatabaseValue.set(originalSet)
        );
        return RedisToken.integer(originalSet.size - initialCount);
    }
}