-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathuser-favorites-controller.ts
More file actions
72 lines (61 loc) · 1.73 KB
/
user-favorites-controller.ts
File metadata and controls
72 lines (61 loc) · 1.73 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import type { FastifyReply, FastifyRequest } from 'fastify'
import {
deleteFavorite,
insertFavorite,
selectFavorite,
selectFavoritesByUser,
} from '@/infra/db/repositories/user-favorites-repository'
import {
checkFavoriteQuerySchema,
getUserFavoritesQuerySchema,
toggleFavoriteBodySchema,
} from '../schemas/user-favorites'
export async function toggleFavoriteController(
request: FastifyRequest,
reply: FastifyReply
) {
const { tmdbId, mediaType, position } = toggleFavoriteBodySchema.parse(
request.body
)
const userId = request.user.id
const existing = await selectFavorite(userId, tmdbId, mediaType)
if (existing) {
await deleteFavorite(userId, tmdbId, mediaType)
return reply.status(200).send({ favorite: null, action: 'removed' })
}
const [favorite] = await insertFavorite({
userId,
tmdbId,
mediaType,
position,
})
return reply.status(200).send({
favorite: {
...favorite,
createdAt: favorite.createdAt.toISOString(),
},
action: 'added',
})
}
export async function getUserFavoritesController(
request: FastifyRequest,
reply: FastifyReply
) {
const { userId } = getUserFavoritesQuerySchema.parse(request.query)
const favorites = await selectFavoritesByUser(userId)
return reply.status(200).send({
favorites: favorites.map(f => ({
...f,
createdAt: f.createdAt.toISOString(),
})),
})
}
export async function checkFavoriteController(
request: FastifyRequest,
reply: FastifyReply
) {
const { tmdbId, mediaType } = checkFavoriteQuerySchema.parse(request.query)
const userId = request.user.id
const favorite = await selectFavorite(userId, Number(tmdbId), mediaType)
return reply.status(200).send({ isFavorite: !!favorite })
}