Repository navigation
Expand file tree
/
Copy pathroutes.js
More file actions
144 lines (114 loc) · 2.76 KB
/
Copy pathroutes.js
File metadata and controls
144 lines (114 loc) · 2.76 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
const { prisma } = require('./prisma.js');
const hashPassword = (pass) => pass;
const setupAuth = (fastify, opts, done) => {
fastify.post('/register', async (req, reply) => {
const { email, name, password } = req.body;
const hashedPassword = hashPassword(password);
const newUser = await prisma.user.create({
data: {
email,
name,
password: hashedPassword,
},
});
const { password: _pass, ...user } = newUser;
req.session.user = user;
return user;
});
fastify.post('/login', async (req, reply) => {
const { email, password } = req.body;
const hashedPassword = hashPassword(password);
const user = await prisma.user.findOne({
where: {
email,
},
});
const { password: userPass, ...userData } = user;
if (userPass != hashedPassword) {
reply.code(401).send({ error: 'User not found.' });
return;
}
req.session.user = userData;
return userData;
});
done();
};
const setupPublicRoutes = (fastify, opts, done) => {
fastify.get('/home', async () => {
const posts = await prisma.post.findMany({
include: {
User: true,
},
});
return posts;
});
fastify.get('/post/:id', async (req) => {
const post = await prisma.post.findOne({
where: { id: parseInt(req.params.id) },
include: {
User: true,
Comment: {
include: {
User: true,
},
},
},
});
return post;
});
fastify.get('/profile/:id', async (req) => {
const user = await prisma.user.findOne({
where: { id: parseInt(req.params.id) },
include: {
Post: true,
},
});
return user;
});
done();
};
const setupWriteRoutes = (fastify, opts, done) => {
fastify.addHook('preHandler', (request, reply, next) => {
if (!request.session.user) {
throw new Error('401');
}
next();
});
fastify.post('/post', async (req) => {
const { title, url, content } = req.body;
const newPost = await prisma.post.create({
data: {
title,
url,
content,
User: {
connect: { id: req.session.user.id },
},
},
});
return newPost;
});
fastify.post('/post/:id/comment', async (req) => {
const { content } = req.body;
const newComment = await prisma.comment.create({
data: {
content,
User: {
connect: { id: req.session.user.id },
},
Post: {
connect: { id: parseInt(req.params.id) },
},
},
});
return newComment;
});
done();
};
exports.setupRoutes = (fastify, opts, done) => {
fastify
.register(setupAuth)
.register(setupPublicRoutes)
.register(setupWriteRoutes);
done();
};