forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vote.ts
29 lines (25 loc) · 766 Bytes
/
vote.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import type { NextApiRequest, NextApiResponse } from 'next'
import redis from '../../lib/redis'
export default async function upvote(
req: NextApiRequest,
res: NextApiResponse
) {
const { title, id } = req.body
const ip =
req.headers['x-forwarded-for'] || req.headers['Remote_Addr'] || 'NA'
const count = ip === 'NA' ? 1 : await redis.sadd('s:' + title, ip)
if (count === 0) {
res.status(400).json({
error: 'You can not vote an item multiple times',
})
} else {
const entry = JSON.parse((await redis.hget('features', id)) || 'null')
const updated = {
...entry,
score: entry.score + 1,
ip,
}
await redis.hset('features', id, JSON.stringify(updated))
return res.status(201).json(updated)
}
}