Skip to content

Commit

Permalink
refactor: get votes routes (#115)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jayllyz authored May 8, 2024
1 parent 68b6960 commit 77d2e2c
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 246 deletions.
6 changes: 3 additions & 3 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
"@hono/zod-validator": "^0.2.1",
"@repo/types": "workspace:*",
"@supabase/supabase-js": "^2.43.1",
"hono": "^4.3.2",
"zod": "^3.23.6",
"hono": "^4.3.3",
"zod": "^3.23.7",
"zod-validation-error": "^3.2.0"
},
"devDependencies": {
"@repo/biome-config": "workspace:*",
"@repo/typescript-config": "workspace:*",
"@types/node": "^20.12.10",
"@types/node": "^20.12.11",
"@types/swagger-ui-dist": "^3.30.4",
"supabase": "^1.165.0",
"tsx": "^4.9.3",
Expand Down
102 changes: 17 additions & 85 deletions apps/api/src/handlers/votes.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import { randomInt } from 'node:crypto';
import crypto from 'node:crypto';
import { OpenAPIHono } from '@hono/zod-openapi';
import { supabase } from '../libs/supabase.js';
import { zodErrorHook } from '../libs/zodError.js';
import {
createPoll,
deletePoll,
getAllPolls,
getOnePoll,
getPollResults,
updatePoll,
voteToPoll,
} from '../routes/votes.js';
import { createPoll, deletePoll, getAllPolls, getOnePoll, updatePoll, voteToPoll } from '../routes/votes.js';
import { checkRole } from '../utils/context.js';
import { getPagination } from '../utils/pagnination.js';
import { Role, type Variables } from '../validators/general.js';
Expand All @@ -24,29 +15,23 @@ polls.openapi(getAllPolls, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, true);
const { skip, take } = c.req.valid('query');
const { from, to } = getPagination(skip, take - 1);
const { all, search, skip, take } = c.req.valid('query');

const { data, error } = await supabase
const query = supabase
.from('POLLS')
.select(
`
id,
title,
description,
start_at,
end_at,
max_choices,
id_user,
results: POLLS_OPTIONS (
id,
content,
votes: POLLS_VOTES (id_option)
)
`,
{ count: 'exact' },
)
.range(from, to);
.select('*, results:POLLS_OPTIONS (id, content, votes:POLLS_VOTES (id_option))', { count: 'exact' })
.order('id', { ascending: true });

if (search) {
query.ilike('title', `%${search}%`);
}

if (!all) {
const { from, to } = getPagination(skip, take - 1);
query.range(from, to);
}

const { data, error } = await query;

if (error) {
return c.json({ error: error.message }, 500);
Expand All @@ -68,23 +53,7 @@ polls.openapi(getOnePoll, async (c) => {

const { data, error } = await supabase
.from('POLLS')
.select(
`
id,
title,
description,
start_at,
end_at,
max_choices,
id_user,
results: POLLS_OPTIONS (
id,
content,
votes: POLLS_VOTES (id_option)
)
`,
{ count: 'exact' },
)
.select('*, results:POLLS_OPTIONS (id, content, votes:POLLS_VOTES (id_option))', { count: 'exact' })
.eq('id', id)
.single();

Expand Down Expand Up @@ -218,9 +187,6 @@ polls.openapi(voteToPoll, async (c) => {
return c.json({ error: 'Failed to vote' }, 400);
}

const randomDelay = randomInt(10, 5000);
setTimeout(async () => {}, randomDelay);

const { data: pollData, error: pollError } = await supabase
.from('USERS_VOTES')
.insert({ id_poll: id, user: hash })
Expand All @@ -232,37 +198,3 @@ polls.openapi(voteToPoll, async (c) => {

return c.json({ message: 'Vote registered' }, 201);
});

type Results = {
id: number;
title: string;
results: { id: number; content: string; votes: number }[];
};

polls.openapi(getPollResults, async (c) => {
const user = c.get('user');
const roles = user.roles;
await checkRole(roles, true);
const { id } = c.req.valid('param');
const { data, error } = await supabase
.from('POLLS')
.select('*, results:POLLS_VOTES(*), options:POLLS_OPTIONS(*)')
.eq('id', id)
.single();

if (error || !data) {
return c.json({ error: 'Poll not found' }, 404);
}

const results: Results = {
id: data.id,
title: data.title,
results: data.options.map((option: { id: number; content: string }) => ({
id: option.id,
content: option.content,
votes: data.results.filter((vote: { id_option: number }) => vote.id_option === option.id).length,
})),
};

return c.json(results, 200);
});
29 changes: 1 addition & 28 deletions apps/api/src/routes/votes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const getAllPolls = createRoute({
security: [{ Bearer: [] }],
middleware: authMiddleware,
request: {
query: queryAllSchema.omit({ search: true, all: true }),
query: queryAllSchema,
},
responses: {
200: {
Expand Down Expand Up @@ -212,30 +212,3 @@ export const voteToPoll = createRoute({
},
tags: ['poll'],
});

export const getPollResults = createRoute({
method: 'get',
path: '/polls/{id}/results',
summary: 'Get poll results',
description: 'Get poll results',
security: [{ Bearer: [] }],
middleware: authMiddleware,
request: {
params: idParamValidator,
},
responses: {
200: {
description: 'Successful response',
content: {
'application/json': {
schema: {
data: pollResultSchema,
},
},
},
},
500: serverErrorSchema,
404: notFoundSchema,
},
tags: ['poll'],
});
Loading

0 comments on commit 77d2e2c

Please sign in to comment.