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 { // handle unsafe integer const valueIsNumberAndNotSafeInteger = !Number.isNaN(Number(value)) && !Number.isSafeInteger(Number(value)); setOwnProperty(obj, key, valueIsNumberAndNotSafeInteger ? value : parseJSON(value)); } catch { setOwnProperty(obj, key, value); } } return obj as TData; } /** * @see https://redis.io/commands/hgetall * @see node_modules/@upstash/redis/docs/commands/hash/hgetall.mdx * Responses are JSON-parsed automatically: a stored "123" comes back as the number 123, "true" as * true, and '{"a":1}' as an object. Pass automaticDeserialization: false to the Redis constructor * to receive raw strings. * With automaticDeserialization: false, hgetall returns a flat array instead, such as * ["text", "123", "version", "1"], and [] for a missing key. */ export class HGetAllCommand> extends Command< unknown | null, TData | null > { constructor(cmd: [key: string], opts?: CommandOptions) { super(["hgetall", ...cmd], { deserialize: (result) => deserialize(result as string[]), ...opts, }); } }