Skip to content

Commit

Permalink
fix(redis): support getKeys and clear with base (#216)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored May 4, 2023
1 parent 333fd44 commit 305472c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
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(":");
}

0 comments on commit 305472c

Please sign in to comment.