All files / src/resp/command/string getset-command.ts

55% Statements 11/20
0% Branches 0/2
50% Functions 1/2
55% Lines 11/20

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 691x   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.
 * ### GETSET key value
 * Atomically sets key to value and returns the old value stored at key. Returns an error when
 * key exists but does not hold a string value.
 *
 * ### Design pattern
 * GETSET can be used together with {@link resp/command/string/incr-command.IncrCommand | INCR} for counting with atomic reset.
 * For example: a process
 * may call INCR against the key mycounter every time some event occurs, but from time to time we
 * need to get the value of the counter and reset it to zero atomically. This can be done using
 * GETSET mycounter "0":
 * ### Example
 * ```
 * redis> INCR mycounter
 * (integer) 1
 * redis> GETSET mycounter "0"
 * "1"
 * redis> GET mycounter
 * "0"
 * redis>
 * ```
 * ### Return value
 * Bulk string reply: the old value stored at key, or nil when key did not exist.
 */
export class GetSetCommand extends IRespCommand {
    public DbDataType = DataType.STRING
 
    public maxParams = 2
 
    public minParams = 2
 
    public name = "getset"
 
    private logger: Logger = new Logger(module.id);
 
    public execSync(request: IRequest, db: Database): RedisToken {
        this.logger.debug(
            `${request.getCommand()}.execute(%s)`,
            ...request.getParams()
        );
        const key: string = request.getParam(0);
        let result: RedisToken;
        const dbValue: DatabaseValue = db.get(key);
        if (!dbValue) {
            result = RedisToken.nullString();
        } else {
            result = RedisToken.string(dbValue.getString());
        }
        const newValue: string = request.getParam(1);
        db.put(
            key,
            new DatabaseValue(
                DataType.STRING,
                newValue
            )
        );
        return result;
    }
}