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

fix(redis): support getKeys and clear with base #216

Merged
merged 2 commits into from
May 4, 2023
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
12 changes: 6 additions & 6 deletions src/drivers/redis.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineDriver } from "./utils";
import { defineDriver, joinKeys } from "./utils";
import Redis, {
Cluster,
ClusterNode,
Expand Down Expand Up @@ -50,7 +50,7 @@ export default defineDriver((opts: RedisOptions = {}) => {
};

const base = (opts.base || "").replace(/:$/, "");
const p = (key: string) => (base ? `${base}:${key}` : key); // Prefix a key. Uses base for backwards compatibility
const p = (...keys: string[]) => joinKeys(base, ...keys); // Prefix a key. Uses base for backwards compatibility
const d = (key: string) => (base ? key.replace(base, "") : key); // Deprefix a key

return {
Expand All @@ -74,12 +74,12 @@ export default defineDriver((opts: RedisOptions = {}) => {
async removeItem(key) {
await getRedisClient().del(p(key));
},
async getKeys() {
const keys: string[] = await getRedisClient().keys(p("*"));
async getKeys(base) {
const keys: string[] = await getRedisClient().keys(p(base, "*"));
return keys.map((key) => d(key));
},
async clear() {
const keys = await getRedisClient().keys(p("*"));
async clear(base) {
const keys = await getRedisClient().keys(p(base, "*"));
if (keys.length === 0) {
return;
}
Expand Down
4 changes: 4 additions & 0 deletions src/drivers/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ export function normalizeKey(key: string | undefined): string {
}
return key.replace(/[/\\]/g, ":").replace(/^:|:$/g, "");
}

export function joinKeys(...keys: string[]) {
return keys.map(normalizeKey).filter(Boolean).join(":");
}