diff --git a/lib/multi-command.spec.ts b/lib/multi-command.spec.ts index 1a9d37b9b9..db68569f3c 100644 --- a/lib/multi-command.spec.ts +++ b/lib/multi-command.spec.ts @@ -1,34 +1,27 @@ import { strict as assert } from 'assert'; -import RedisMultiCommand, { MultiQueuedCommand } from './multi-command'; -import RedisClient from './client'; +import RedisMultiCommand from './multi-command'; +import RedisCommandsQueue from './commands-queue'; describe('Multi Command', () => { - it('create', async () => { - const multi = RedisMultiCommand.create(async (encodedCommands: Array): Promise> => { - return Object.keys(encodedCommands); + it('simple', async () => { + const multi = RedisMultiCommand.create(queue => { + assert.deepEqual( + queue.map(({encodedCommand}) => encodedCommand), + [ + RedisCommandsQueue.encodeCommand(['MULTI']), + RedisCommandsQueue.encodeCommand(['PING']), + RedisCommandsQueue.encodeCommand(['EXEC']), + ] + ); + + return Promise.resolve(['PONG']); }); multi.ping(); - multi.set('a', 'b'); - // console.log( - await multi.exec() - // ); - }); - - it('client.multi', async () => { - const client = RedisClient.create(); - - await client.connect(); assert.deepEqual( - await client - .multi() - .ping() - .set('key', 'value') - .exec(), - ['PONG', 'OK'] + await multi.exec(), + ['PONG'] ); - - await client.disconnect(); }); }); diff --git a/lib/multi-command.ts b/lib/multi-command.ts index 054f6bb41f..9e5821bc6c 100644 --- a/lib/multi-command.ts +++ b/lib/multi-command.ts @@ -19,7 +19,7 @@ export interface MultiQueuedCommand { transformReply?: RedisCommand['transformReply']; } -export type RedisMultiExecutor = (encodedCommands: Array, chainId: Symbol) => Promise>; +export type RedisMultiExecutor = (queue: Array, chainId: Symbol) => Promise>; export default class RedisMultiCommand { static defineCommand(on: any, name: string, command: RedisCommand) { @@ -61,9 +61,21 @@ export default class RedisMultiCommand { } async exec(): Promise> { - const results = await this.#executor(this.#queue, Symbol('[RedisMultiCommand] Chain ID')); - return this.#queue.map(({transformReply}, i) => { - const reply = results[i]; + if (!this.#queue.length) { + return []; + } + + const queue = this.#queue.splice(0); + queue.unshift({ + encodedCommand: RedisCommandsQueue.encodeCommand(['MULTI']) + }); + queue.push({ + encodedCommand: RedisCommandsQueue.encodeCommand(['EXEC']) + }); + + const rawReplies = await this.#executor(queue, Symbol('[RedisMultiCommand] Chain ID')); + return rawReplies.map((reply, i) => { + const { transformReply } = queue[i + 1]; return transformReply ? transformReply(reply) : reply; }); };