1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-01 16:46:54 +03:00
Files
node-redis/packages/client/lib/multi-command.ts
Shaya Potter 4708736f3b new "transform arguments" API for better key and metadata extraction (#2733)
* Parser support with all commands

* remove "dist" from all imports for consistency

* address most of my review comments

* small tweak to multi type mapping handling

* tweak multi commands / fix addScript cases

* nits

* addressed all in person review comments

* revert addCommand/addScript changes to multi-commands

addCommand needs to be there for sendCommand like ability within a multi.

If its there, it might as well be used by createCommand() et al, to avoid repeating code.

addScript is there (even though only used once), but now made private to keep the logic for bookkeeping near each other.
2024-10-31 12:16:59 -04:00

71 lines
2.0 KiB
TypeScript

import { CommandArguments, RedisScript, ReplyUnion, TransformReply, TypeMapping } from './RESP/types';
import { ErrorReply, MultiErrorReply } from './errors';
export type MULTI_REPLY = {
GENERIC: 'generic';
TYPED: 'typed';
};
export type MultiReply = MULTI_REPLY[keyof MULTI_REPLY];
export type MultiReplyType<T extends MultiReply, REPLIES> = T extends MULTI_REPLY['TYPED'] ? REPLIES : Array<ReplyUnion>;
export interface RedisMultiQueuedCommand {
args: CommandArguments;
transformReply?: TransformReply;
}
export default class RedisMultiCommand {
private readonly typeMapping?: TypeMapping;
constructor(typeMapping?: TypeMapping) {
this.typeMapping = typeMapping;
}
readonly queue: Array<RedisMultiQueuedCommand> = [];
readonly scriptsInUse = new Set<string>();
addCommand(args: CommandArguments, transformReply?: TransformReply) {
this.queue.push({
args,
transformReply
});
}
addScript(script: RedisScript, args: CommandArguments, transformReply?: TransformReply) {
const redisArgs: CommandArguments = [];
redisArgs.preserve = args.preserve;
if (this.scriptsInUse.has(script.SHA1)) {
redisArgs.push('EVALSHA', script.SHA1);
} else {
this.scriptsInUse.add(script.SHA1);
redisArgs.push('EVAL', script.SCRIPT);
}
if (script.NUMBER_OF_KEYS !== undefined) {
redisArgs.push(script.NUMBER_OF_KEYS.toString());
}
redisArgs.push(...args);
this.addCommand(redisArgs, transformReply);
}
transformReplies(rawReplies: Array<unknown>): Array<unknown> {
const errorIndexes: Array<number> = [],
replies = rawReplies.map((reply, i) => {
if (reply instanceof ErrorReply) {
errorIndexes.push(i);
return reply;
}
const { transformReply, args } = this.queue[i];
return transformReply ? transformReply(reply, args.preserve, this.typeMapping) : reply;
});
if (errorIndexes.length) throw new MultiErrorReply(replies, errorIndexes);
return replies;
}
}