Last active
April 15, 2023 16:55
-
-
Save benjaminudoh10/f9006aafb637b9fc67dc1376f22a99eb to your computer and use it in GitHub Desktop.
Add reaction to feed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Redis from 'ioredis'; | |
export class ReactionService { | |
private redisClient: Redis | |
constructor() { | |
// connect to your redis instance first | |
this.redisClient = new Redis() | |
} | |
async addReactionToFeed( | |
userID: string, | |
{ type, feedID }: ReactionInput | |
) { | |
const key = `${feedID}:${type}` | |
await this.redisClient.sadd(key, userID) | |
return { success: true } | |
} | |
async removeReactionFromFeed( | |
userID: string, | |
{ type, feedID }: ReactionInput | |
) { | |
const key = `${feedID}:${type}` | |
// this check is not really important as redis will handle the case | |
// where the item is not in the set | |
const isMember = await this.redisClient.sismember(key, userID) | |
if (isMember) { | |
await this.redisClient.srem(key, userID) | |
} | |
return { success: true } | |
} | |
async getFeedReactions(feedID: string) { | |
// Reactions is an enum | |
const [DEAD, STRENGTH, HEART, LIKE] = await Promise.all([ | |
this.redisClient.scard(`${feedID}:${Reactions.DEAD}`), | |
this.redisClient.scard(`${feedID}:${Reactions.STRENGTH}`), | |
this.redisClient.scard(`${feedID}:${Reactions.HEART}`), | |
this.redisClient.scard(`${feedID}:${Reactions.LIKE}`), | |
]) | |
return { | |
DEAD, STRENGTH, HEART, LIKE | |
} | |
} | |
async removeReactionsForFeed(feedID: string) { | |
// this is used when the feed item is deleted | |
await Promise.all([ | |
this.redisClient.del(`${feedID}:${Reactions.DEAD}`), | |
this.redisClient.del(`${feedID}:${Reactions.STRENGTH}`), | |
this.redisClient.del(`${feedID}:${Reactions.HEART}`), | |
this.redisClient.del(`${feedID}:${Reactions.LIKE}`), | |
]) | |
return { success: true } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment