add followings cache

This commit is contained in:
Namekuji 2023-07-26 21:24:56 -04:00
parent f0ce2808d9
commit e4fef88e4e
No known key found for this signature in database
GPG key ID: 1D62332C07FBA532

View file

@ -1,6 +1,7 @@
import { redisClient } from "@/db/redis.js"; import { redisClient } from "@/db/redis.js";
import { encode, decode } from "msgpackr"; import { encode, decode } from "msgpackr";
import { ChainableCommander } from "ioredis"; import { ChainableCommander } from "ioredis";
import { Followings } from "@/models/index.js";
export class Cache<T> { export class Cache<T> {
private ttl: number; private ttl: number;
@ -129,3 +130,44 @@ export class Cache<T> {
return value; return value;
} }
} }
export class FollowingsCache {
private myId: string;
private key: string;
private constructor(userId: string) {
this.myId = userId;
this.key = `followings:${userId}`;
}
public static async init(userId: string) {
const cache = new FollowingsCache(userId);
// Sync from DB if no relationships is cached
if ((await redisClient.scard(cache.key)) === 0) {
const rel = await Followings.find({
select: { followeeId: true },
where: { followerId: cache.myId },
});
await cache.follow(...rel.map((r) => r.followeeId));
}
return cache;
}
public async follow(...targetIds: string[]) {
if (targetIds.length > 0) {
await redisClient.sadd(this.key, targetIds);
}
}
public async unfollow(...targetIds: string[]) {
if (targetIds.length > 0) {
await redisClient.srem(this.key, targetIds);
}
}
public async isFollowing(targetId: string): Promise<boolean> {
return (await redisClient.sismember(this.key, targetId)) === 1;
}
}