-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaylists.js
66 lines (59 loc) · 1.82 KB
/
playlists.js
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
const express = require("express");
const { PrismaClient } = require("@prisma/client");
const bcrypt = require("bcrypt");
const router = express.Router();
const prisma = new PrismaClient();
router.post("/", async (req, res) => {
const { username, password, name, description, trackIds } = req.body;
try {
const user = await prisma.user.findUnique({
where: { username },
});
if (!user) {
return res.status(401).json({ error: "Unauthorized: Nah" });
}
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return res.status(401).json({ error: "Unauthorized: WRONG" });
}
const validTracks = await prisma.track.findMany({
where: {
id: { in: trackIds },
},
});
if (validTracks.length !== trackIds.length) {
return res.status(400).json({
error: "One or more track IDs are invalid",
});
}
const newPlaylist = await prisma.playlist.create({
data: {
name,
description,
owner: { connect: { id: user.id } },
tracks: { connect: trackIds.map((id) => ({ id })) },
},
});
res.status(201).json(newPlaylist);
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
router.get('/:id', async (req, res) => {
const playlistId = parseInt(req.params.id);
try {
const playlist = await prisma.playlist.findUnique({
where: { id: playlistId },
include: { tracks: true, owner: true },
});
if (!playlist) {
return res.status(404).json({ error: 'Playlist not found' });
}
res.json(playlist);
} catch (error) {
console.error('Error fetching playlist:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
module.exports = router;