import { parseJSON, setOwnProperty } from "../util"; import type { CommandOptions } from "./command"; import { Command } from "./command"; function deserialize>(result: string[]): TData | null { if (result.length === 0) { return null; } const obj: Record = {}; for (let i = 0; i < result.length; i += 2) { const key = result[i]; const value = result[i + 1]; try { setOwnProperty(obj, key, parseJSON(value)); } catch { setOwnProperty(obj, key, value); } } return obj as TData; } /** * @see https://redis.io/commands/hrandfield * @see node_modules/@upstash/redis/docs/commands/hash/hrandfield.mdx */ export class HRandFieldCommand< TData extends string | string[] | Record, > extends Command { constructor(cmd: [key: string], opts?: CommandOptions); constructor(cmd: [key: string, count: number], opts?: CommandOptions); constructor( cmd: [key: string, count: number, withValues: boolean], opts?: CommandOptions> ); constructor( cmd: [key: string, count?: number, withValues?: boolean], opts?: CommandOptions> ) { const command = ["hrandfield", cmd[0]] as unknown[]; if (typeof cmd[1] === "number") { command.push(cmd[1]); } if (cmd[2]) { command.push("WITHVALUES"); } super(command, { // @ts-expect-error to silence compiler deserialize: cmd[2] ? (result) => deserialize(result as string[]) : opts?.deserialize, ...opts, }); } }