aboutsummaryrefslogtreecommitdiff
path: root/utils/getRedisWithPrefix.js
blob: b85589b6684a618c75c1c90bcbfb97dfaab5dead (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { redis } from "@/lib/redis";

export async function getValuesWithPrefix(prefix) {
  let cursor = "0"; // Start at the beginning of the keyspace
  let values = [];

  do {
    const [newCursor, matchingKeys] = await redis.scan(
      cursor,
      "MATCH",
      prefix + "*",
      "COUNT",
      100
    );

    // Retrieve values for matching keys and add them to the array
    for (const key of matchingKeys) {
      const value = await redis.get(key);
      values.push(JSON.parse(value));
    }

    // Update the cursor for the next iteration
    cursor = newCursor;
  } while (cursor !== "0"); // Continue until the cursor is '0'

  return values;
}

export async function countKeysWithPrefix(prefix) {
  let cursor = "0"; // Start at the beginning of the keyspace
  let count = 0;

  do {
    const [newCursor, matchingKeys] = await redis.scan(
      cursor,
      "MATCH",
      prefix + "*",
      "COUNT",
      100
    );

    // Increment the count by the number of matching keys in this iteration
    count += matchingKeys.length;

    // Update the cursor for the next iteration
    cursor = newCursor;
  } while (cursor !== "0"); // Continue until the cursor is '0'

  return count;
}

export async function getValuesWithNumericKeys() {
  const allKeys = await redis.keys("*"); // Fetch all keys in Redis
  const numericKeys = allKeys.filter((key) => /^\d+$/.test(key)); // Filter keys that contain only numbers

  const values = [];

  for (const key of numericKeys) {
    const value = await redis.get(key); // Retrieve the value for each numeric key
    values.push(value);
  }

  return values;
}

export async function getKeysWithNumericKeys() {
  const allKeys = await redis.keys("*"); // Fetch all keys in Redis
  const numericKeys = allKeys.filter((key) => /^\d+$/.test(key)); // Filter keys that contain only numbers

  const values = [];

  for (const key of numericKeys) {
    const value = await redis.del(key);
  }

  return values;
}

export async function countNumericKeys() {
  const allKeys = await redis.keys("*"); // Fetch all keys in Redis
  const numericKeys = allKeys.filter((key) => /^\d+$/.test(key)); // Filter keys that contain only numbers

  return numericKeys.length; // Return the count of numeric keys
}