Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added command: getex #1358

Merged
merged 5 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkg/auto-pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe("Auto pipeline", () => {
redis.get(newKey()),
redis.getbit(newKey(), 0),
redis.getdel(newKey()),
redis.getex(newKey()),
redis.getset(newKey(), "hello"),
redis.hdel(newKey(), "field"),
redis.hexists(newKey(), "field"),
Expand Down Expand Up @@ -148,7 +149,7 @@ describe("Auto pipeline", () => {
redis.json.arrappend(persistentKey3, "$.log", '"three"'),
]);
expect(result).toBeTruthy();
expect(result.length).toBe(121); // returns
expect(result.length).toBe(122); // returns
// @ts-expect-error pipelineCounter is not in type but accessible120 results
expect(redis.pipelineCounter).toBe(1);
});
Expand Down
22 changes: 11 additions & 11 deletions pkg/commands/exec.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { type CommandOptions, Command } from "./command";
import { type CommandOptions, Command } from "./command";

/**
* Generic exec command for executing arbitrary Redis commands
* Allows executing Redis commands that might not be directly supported by the SDK
*
*
* @example
* // Execute MEMORY USAGE command
* await redis.exec<number>("MEMORY", "USAGE", "myKey")
*
*
* // Execute GET command
* await redis.exec<string>("GET", "foo")
*/

export class ExecCommand<TResult> extends Command<TResult, TResult> {
constructor(
cmd: [command: string, ...args: (string | number | boolean)[]],
opts?: CommandOptions<TResult, TResult>
){
const normalizedCmd = cmd.map(arg => typeof arg === "string" ? arg : String(arg));
super(normalizedCmd, opts);
}
}
constructor(
cmd: [command: string, ...args: (string | number | boolean)[]],
opts?: CommandOptions<TResult, TResult>
) {
const normalizedCmd = cmd.map((arg) => (typeof arg === "string" ? arg : String(arg)));
super(normalizedCmd, opts);
}
}
112 changes: 112 additions & 0 deletions pkg/commands/getex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { keygen, newHttpClient, randomID } from "../test-utils";

import { afterAll, describe, expect, test } from "bun:test";
import { GetExCommand } from "./getex";
import { GetCommand } from "./get";
import { SetCommand } from "./set";

const client = newHttpClient();

const { newKey, cleanup } = keygen();
afterAll(cleanup);

describe("without options", () => {
test("gets value", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([key]).exec(client);
expect(res2).toEqual(value);
});
});

describe("ex", () => {
test("gets value and sets expiry in seconds", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([key, { ex: 1 }]).exec(client);
expect(res2).toEqual(value);
await new Promise((res) => setTimeout(res, 2000));

const res3 = await new GetCommand([key]).exec(client);
expect(res3).toEqual(null);
});
});

describe("px", () => {
test("gets value and sets expiry in milliseconds", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([key, { px: 1000 }]).exec(client);
expect(res2).toEqual(value);
await new Promise((res) => setTimeout(res, 2000));

const res3 = await new GetCommand([key]).exec(client);

expect(res3).toEqual(null);
});
});

describe("exat", () => {
test("gets value and sets expiry in Unix time (seconds)", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([
key,
{
exat: Math.floor(Date.now() / 1000) + 2,
},
]).exec(client);
expect(res2).toEqual(value);
await new Promise((res) => setTimeout(res, 3000));

const res3 = await new GetCommand([key]).exec(client);

expect(res3).toEqual(null);
});
});

describe("pxat", () => {
test("gets value and sets expiry in Unix time (milliseconds)", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([key, { pxat: Date.now() + 2000 }]).exec(client);
expect(res2).toEqual(value);
await new Promise((res) => setTimeout(res, 3000));

const res3 = await new GetCommand([key]).exec(client);

expect(res3).toEqual(null);
});
});

describe("persist", () => {
test("gets value and removes expiry", async () => {
const key = newKey();
const value = randomID();

const res = await new SetCommand([key, value, { ex: 1 }]).exec(client);
expect(res).toEqual("OK");
const res2 = await new GetExCommand([key, { persist: true }]).exec(client);
expect(res2).toEqual(value);
await new Promise((res) => setTimeout(res, 2000));

const res3 = await new GetCommand([key]).exec(client);

expect(res3).toEqual(value);
});
});
36 changes: 36 additions & 0 deletions pkg/commands/getex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { CommandOptions } from "./command";
import { Command } from "./command";

type GetExCommandOptions =
| { ex: number; px?: never; exat?: never; pxat?: never; persist?: never }
| { ex?: never; px: number; exat?: never; pxat?: never; persist?: never }
| { ex?: never; px?: never; exat: number; pxat?: never; persist?: never }
| { ex?: never; px?: never; exat?: never; pxat: number; persist?: never }
| { ex?: never; px?: never; exat?: never; pxat?: never; persist: true }
| { ex?: never; px?: never; exat?: never; pxat?: never; persist?: never };

/**
* @see https://redis.io/commands/getex
*/
export class GetExCommand<TData = string> extends Command<unknown | null, TData | null> {
constructor(
[key, opts]: [key: string, opts?: GetExCommandOptions],
cmdOpts?: CommandOptions<unknown | null, TData | null>
) {
const command: unknown[] = ["getex", key];
if (opts) {
if ("ex" in opts && typeof opts.ex === "number") {
command.push("ex", opts.ex);
} else if ("px" in opts && typeof opts.px === "number") {
command.push("px", opts.px);
} else if ("exat" in opts && typeof opts.exat === "number") {
command.push("exat", opts.exat);
} else if ("pxat" in opts && typeof opts.pxat === "number") {
command.push("pxat", opts.pxat);
} else if ("persist" in opts && opts.persist) {
command.push("persist");
}
}
super(command, cmdOpts);
}
}
1 change: 1 addition & 0 deletions pkg/commands/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export * from "./geo_search_store";
export * from "./get";
export * from "./getbit";
export * from "./getdel";
export * from "./getex";
export * from "./getrange";
export * from "./getset";
export * from "./hdel";
Expand Down
1 change: 1 addition & 0 deletions pkg/commands/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export { type GeoSearchStoreCommand } from "./geo_search_store";
export { type GetCommand } from "./get";
export { type GetBitCommand } from "./getbit";
export { type GetDelCommand } from "./getdel";
export { type GetExCommand } from "./getex";
export { type GetRangeCommand } from "./getrange";
export { type GetSetCommand } from "./getset";
export { type HDelCommand } from "./hdel";
Expand Down
11 changes: 6 additions & 5 deletions pkg/pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ describe("use all the things", () => {
.get(newKey())
.getbit(newKey(), 0)
.getdel(newKey())
.getex(newKey())
.getset(newKey(), "hello")
.hdel(newKey(), "field")
.hexists(newKey(), "field")
Expand Down Expand Up @@ -249,15 +250,15 @@ describe("use all the things", () => {
.json.set(newKey(), "$", { hello: "world" });

const res = await p.exec();
expect(res.length).toEqual(121);
expect(res.length).toEqual(122);
});
});
describe("keep errors", () => {
test("should return results in case of success", async () => {
const p = new Pipeline({ client });
p.set("foo", "1");
p.set("bar", "2");
p.get("foo");
p.getex("foo", { ex: 1 });
p.get("bar");
const results = await p.exec({ keepErrors: true });

Expand Down Expand Up @@ -286,18 +287,18 @@ describe("keep errors", () => {
p.set("foo", "1");
p.set("bar", "2");
p.evalsha("wrong-sha1", [], []);
p.get("foo");
p.getex("foo", { exat: 123 });
p.get("bar");
const results = await p.exec<[string, string, string, number, number]>({ keepErrors: true });

expect(results[0].error).toBeUndefined();
expect(results[1].error).toBeUndefined();
expect(results[2].error).toBe("NOSCRIPT No matching script. Please use EVAL.");
expect(results[3].error).toBeUndefined();
expect(results[3].error).toBe("ERR invalid expire time");
expect(results[4].error).toBeUndefined();

expect(results[2].result).toBeUndefined();
expect(results[3].result).toBe(1);
expect(results[3].result).toBeUndefined();
expect(results[4].result).toBe(2);
});
});
6 changes: 6 additions & 0 deletions pkg/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
GetBitCommand,
GetCommand,
GetDelCommand,
GetExCommand,
GetRangeCommand,
GetSetCommand,
HDelCommand,
Expand Down Expand Up @@ -544,6 +545,11 @@ export class Pipeline<TCommands extends Command<any, any>[] = []> {
*/
getdel = <TData>(...args: CommandArgs<typeof GetDelCommand>) =>
this.chain(new GetDelCommand<TData>(args, this.commandOptions));
/**
* @see https://redis.io/commands/getex
*/
getex = <TData>(...args: CommandArgs<typeof GetExCommand>) =>
this.chain(new GetExCommand<TData>(args, this.commandOptions));
/**
* @see https://redis.io/commands/getrange
*/
Expand Down
7 changes: 7 additions & 0 deletions pkg/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
GetBitCommand,
GetCommand,
GetDelCommand,
GetExCommand,
GetRangeCommand,
GetSetCommand,
HDelCommand,
Expand Down Expand Up @@ -621,6 +622,12 @@ export class Redis {
getdel = <TData>(...args: CommandArgs<typeof GetDelCommand>) =>
new GetDelCommand<TData>(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/getex
*/
getex = <TData>(...args: CommandArgs<typeof GetExCommand>) =>
new GetExCommand<TData>(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/getrange
*/
Expand Down