Skip to content

Commit

Permalink
votes ranking system
Browse files Browse the repository at this point in the history
  • Loading branch information
brunodsousa committed Feb 12, 2024
1 parent bb47fcb commit ec3e9b8
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 1 deletion.
79 changes: 79 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@fastify/cookie": "^9.3.1",
"@prisma/client": "^5.9.1",
"fastify": "^4.26.0",
"ioredis": "^5.3.2",
"zod": "^3.22.4"
}
}
29 changes: 28 additions & 1 deletion src/http/routes/get-poll.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import z from "zod";
import { prisma } from "../../lib/prisma";
import { redis } from "../../lib/redis";

export async function getPoll(app: FastifyInstance) {
app.get(
Expand All @@ -26,7 +27,33 @@ export async function getPoll(app: FastifyInstance) {
},
});

return reply.send({ poll });
if (!poll) {
return reply.status(404).send({ message: "Poll not found." });
}

const result = await redis.zrange(pollId, 0, -1, "WITHSCORES");

const votes = result.reduce((obj, line, index) => {
if (index % 2 === 0) {
const score = result[index + 1];
Object.assign(obj, { [line]: Number(score) });
}
return obj;
}, {} as Record<string, number>);

return reply.send({
poll: {
id: poll.id,
title: poll.title,
options: poll.options.map((option) => {
return {
id: option.id,
title: option.title,
score: option.id in votes ? votes[option.id] : 0,
};
}),
},
});
}
);
}
5 changes: 5 additions & 0 deletions src/http/routes/vote-on-poll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import z from "zod";
import { randomUUID } from "node:crypto";
import { prisma } from "../../lib/prisma";
import { redis } from "../../lib/redis";

export async function voteOnPoll(app: FastifyInstance) {
app.post(
Expand Down Expand Up @@ -39,6 +40,8 @@ export async function voteOnPoll(app: FastifyInstance) {
id: userPreviousVoteOnPoll.id,
},
});

await redis.zincrby(pollId, -1, userPreviousVoteOnPoll.pollOptionId);
} else if (userPreviousVoteOnPoll) {
return reply
.status(400)
Expand All @@ -65,6 +68,8 @@ export async function voteOnPoll(app: FastifyInstance) {
},
});

await redis.zincrby(pollId, 1, pollOptionId);

return reply.status(201);
}
);
Expand Down
3 changes: 3 additions & 0 deletions src/lib/redis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { Redis } from "ioredis";

export const redis = new Redis();

0 comments on commit ec3e9b8

Please sign in to comment.