Skip to content

Commit

Permalink
Merge pull request #9 from La-404-Devinci/feat/redis-sets
Browse files Browse the repository at this point in the history
feat: add sorted sets functions to redis
  • Loading branch information
Kan-A-Pesh authored Nov 4, 2024
2 parents 65168b7 + dc4400f commit 9638b29
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions database/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,33 @@ export default abstract class Redis {
public static async del(key: string): Promise<void> {
await Redis.client.del(key);
}

public static async sortedSet<T>(setName: string, score: number, data: T): Promise<void> {
const stringValue = JSON.stringify(data);

await Redis.client.zAdd(setName, {
value: stringValue,
score
});
}

public static async sortedRemove<T>(setName: string, data: T): Promise<void> {
const stringValue = JSON.stringify(data);
await Redis.client.zRem(setName, stringValue);
}

public static async sortedAll<T>(setName: string): Promise<{ value: T; score: number }[]> {
const data = await Redis.client.zRangeWithScores(setName, 0, -1);

return data.map(({ value, score }) => ({
value: JSON.parse(value) as T,
score
}));
}

public static async sortedGetScore<T>(setName: string, data: T): Promise<number> {
const stringValue = JSON.stringify(data);
const score = await Redis.client.zScore(setName, stringValue);
return score ? score : 0;
}
}

0 comments on commit 9638b29

Please sign in to comment.