333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const commands = require("redis-commands");
const calculateSlot = require("cluster-key-slot");
const standard_as_callback_1 = require("standard-as-callback");
const utils_1 = require("./utils");
const lodash_1 = require("./utils/lodash");
const promiseContainer_1 = require("./promiseContainer");
/**
 * Command instance
 *
 * It's rare that you need to create a Command instance yourself.
 *
 * @export
 * @class Command
 *
 * @example
 * ```js
 * var infoCommand = new Command('info', null, function (err, result) {
 *   console.log('result', result);
 * });
 *
 * redis.sendCommand(infoCommand);
 *
 * // When no callback provided, Command instance will have a `promise` property,
 * // which will resolve/reject with the result of the command.
 * var getCommand = new Command('get', ['foo']);
 * getCommand.promise.then(function (result) {
 *   console.log('result', result);
 * });
 * ```
 * @see {@link Redis#sendCommand} which can send a Command instance to Redis
 */
class Command {
    /**
     * Creates an instance of Command.
     * @param {string} name Command name
     * @param {(Array<string | Buffer | number>)} [args=[]] An array of command arguments
     * @param {ICommandOptions} [options={}]
     * @param {CallbackFunction} [callback] The callback that handles the response.
     * If omit, the response will be handled via Promise
     * @memberof Command
     */
    constructor(name, args = [], options = {}, callback) {
        this.name = name;
        this.transformed = false;
        this.isCustomCommand = false;
        this.replyEncoding = options.replyEncoding;
        this.errorStack = options.errorStack;
        this.args = lodash_1.flatten(args);
        this.callback = callback;
        this.initPromise();
        if (options.keyPrefix) {
            this._iterateKeys(key => options.keyPrefix + key);
        }
    }
    static getFlagMap() {
        if (!this.flagMap) {
            this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => {
                map[flagName] = {};
                Command.FLAGS[flagName].forEach(commandName => {
                    map[flagName][commandName] = true;
                });
                return map;
            }, {});
        }
        return this.flagMap;
    }
    /**
     * Check whether the command has the flag
     *
     * @param {string} flagName
     * @param {string} commandName
     * @return {boolean}
     */
    static checkFlag(flagName, commandName) {
        return !!this.getFlagMap()[flagName][commandName];
    }
    static setArgumentTransformer(name, func) {
        this._transformer.argument[name] = func;
    }
    static setReplyTransformer(name, func) {
        this._transformer.reply[name] = func;
    }
    initPromise() {
        const Promise = promiseContainer_1.get();
        const promise = new Promise((resolve, reject) => {
            if (!this.transformed) {
                this.transformed = true;
                const transformer = Command._transformer.argument[this.name];
                if (transformer) {
                    this.args = transformer(this.args);
                }
                this.stringifyArguments();
            }
            this.resolve = this._convertValue(resolve);
            if (this.errorStack) {
                this.reject = err => {
                    reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname));
                };
            }
            else {
                this.reject = reject;
            }
        });
        this.promise = standard_as_callback_1.default(promise, this.callback);
    }
    getSlot() {
        if (typeof this.slot === "undefined") {
            const key = this.getKeys()[0];
            this.slot = key == null ? null : calculateSlot(key);
        }
        return this.slot;
    }
    getKeys() {
        return this._iterateKeys();
    }
    /**
     * Iterate through the command arguments that are considered keys.
     *
     * @param {Function} [transform=(key) => key] The transformation that should be applied to
     * each key. The transformations will persist.
     * @returns {string[]} The keys of the command.
     * @memberof Command
     */
    _iterateKeys(transform = key => key) {
        if (typeof this.keys === "undefined") {
            this.keys = [];
            if (commands.exists(this.name)) {
                const keyIndexes = commands.getKeyIndexes(this.name, this.args);
                for (const index of keyIndexes) {
                    this.args[index] = transform(this.args[index]);
                    this.keys.push(this.args[index]);
                }
            }
        }
        return this.keys;
    }
    /**
     * Convert command to writable buffer or string
     *
     * @return {string|Buffer}
     * @see {@link Redis#sendCommand}
     * @public
     */
    toWritable() {
        let bufferMode = false;
        for (const arg of this.args) {
            if (arg instanceof Buffer) {
                bufferMode = true;
                break;
            }
        }
        let result;
        let commandStr = "*" +
            (this.args.length + 1) +
            "\r\n$" +
            Buffer.byteLength(this.name) +
            "\r\n" +
            this.name +
            "\r\n";
        if (bufferMode) {
            const buffers = new MixedBuffers();
            buffers.push(commandStr);
            for (const arg of this.args) {
                if (arg instanceof Buffer) {
                    if (arg.length === 0) {
                        buffers.push("$0\r\n\r\n");
                    }
                    else {
                        buffers.push("$" + arg.length + "\r\n");
                        buffers.push(arg);
                        buffers.push("\r\n");
                    }
                }
                else {
                    buffers.push("$" +
                        Buffer.byteLength(arg) +
                        "\r\n" +
                        arg +
                        "\r\n");
                }
            }
            result = buffers.toBuffer();
        }
        else {
            result = commandStr;
            for (const arg of this.args) {
                result +=
                    "$" +
                        Buffer.byteLength(arg) +
                        "\r\n" +
                        arg +
                        "\r\n";
            }
        }
        return result;
    }
    stringifyArguments() {
        for (let i = 0; i < this.args.length; ++i) {
            const arg = this.args[i];
            if (!(arg instanceof Buffer) && typeof arg !== "string") {
                this.args[i] = utils_1.toArg(arg);
            }
        }
    }
    /**
     * Convert the value from buffer to the target encoding.
     *
     * @private
     * @param {Function} resolve The resolve function of the Promise
     * @returns {Function} A funtion to transform and resolve a value
     * @memberof Command
     */
    _convertValue(resolve) {
        return value => {
            try {
                resolve(this.transformReply(value));
            }
            catch (err) {
                this.reject(err);
            }
            return this.promise;
        };
    }
    /**
     * Convert buffer/buffer[] to string/string[],
     * and apply reply transformer.
     *
     * @memberof Command
     */
    transformReply(result) {
        if (this.replyEncoding) {
            result = utils_1.convertBufferToString(result, this.replyEncoding);
        }
        const transformer = Command._transformer.reply[this.name];
        if (transformer) {
            result = transformer(result);
        }
        return result;
    }
}
Command.FLAGS = {
    VALID_IN_SUBSCRIBER_MODE: [
        "subscribe",
        "psubscribe",
        "unsubscribe",
        "punsubscribe",
        "ping",
        "quit"
    ],
    VALID_IN_MONITOR_MODE: ["monitor", "auth"],
    ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"],
    EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"],
    WILL_DISCONNECT: ["quit"]
};
Command._transformer = {
    argument: {},
    reply: {}
};
exports.default = Command;
const msetArgumentTransformer = function (args) {
    if (args.length === 1) {
        if (typeof Map !== "undefined" && args[0] instanceof Map) {
            return utils_1.convertMapToArray(args[0]);
        }
        if (typeof args[0] === "object" && args[0] !== null) {
            return utils_1.convertObjectToArray(args[0]);
        }
    }
    return args;
};
Command.setArgumentTransformer("mset", msetArgumentTransformer);
Command.setArgumentTransformer("msetnx", msetArgumentTransformer);
Command.setArgumentTransformer("hmset", function (args) {
    if (args.length === 2) {
        if (typeof Map !== "undefined" && args[1] instanceof Map) {
            return [args[0]].concat(utils_1.convertMapToArray(args[1]));
        }
        if (typeof args[1] === "object" && args[1] !== null) {
            return [args[0]].concat(utils_1.convertObjectToArray(args[1]));
        }
    }
    return args;
});
Command.setReplyTransformer("hgetall", function (result) {
    if (Array.isArray(result)) {
        var obj = {};
        for (var i = 0; i < result.length; i += 2) {
            obj[result[i]] = result[i + 1];
        }
        return obj;
    }
    return result;
});
class MixedBuffers {
    constructor() {
        this.length = 0;
        this.items = [];
    }
    push(x) {
        this.length += Buffer.byteLength(x);
        this.items.push(x);
    }
    toBuffer() {
        const result = Buffer.allocUnsafe(this.length);
        let offset = 0;
        for (const item of this.items) {
            const length = Buffer.byteLength(item);
            Buffer.isBuffer(item)
                ? item.copy(result, offset)
                : result.write(item, offset, length);
            offset += length;
        }
        return result;
    }
}