Skip to content

Instantly share code, notes, and snippets.

@benjaminudoh10
Last active April 15, 2023 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjaminudoh10/f9006aafb637b9fc67dc1376f22a99eb to your computer and use it in GitHub Desktop.
Save benjaminudoh10/f9006aafb637b9fc67dc1376f22a99eb to your computer and use it in GitHub Desktop.
Add reaction to feed
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