-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
95 lines (86 loc) · 2.47 KB
/
server.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
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
const express = require('express');
const cors = require('cors');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(cors());
server.use(express.json());
server.get('/api/goals', async (req, res) => {
try {
const goals = await prisma.goal.findMany({
where: {
userId: parseInt(req.query.userId, 10),
},
include: {
user: true,
},
});
res.json(goals);
} catch (error) {
console.error('Error fetching goals:', error);
res.status(500).json({ message: 'Failed to fetch goals' });
}
});
server.post('/api/goals', async (req, res) => {
try {
const { name, target, userId } = req.body;
const newGoal = await prisma.goal.create({
data: {
name,
target,
userId: parseInt(userId, 10),
},
});
res.status(201).json(newGoal);
} catch (error) {
console.error('Error creating goal:', error);
res.status(500).json({ message: 'Failed to create goal' });
}
});
server.get('/api/activities', async (req, res) => {
try {
const activities = await prisma.activity.findMany({
where: {
userId: parseInt(req.query.userId, 10),
},
include: {
user: true,
},
});
res.json(activities);
} catch (error) {
console.error('Error fetching activities:', error);
res.status(500).json({ message: 'Failed to fetch activities' });
}
});
server.post('/api/activities', async (req, res) => {
try {
const { type, date, duration, caloriesBurned, userId } = req.body;
const newActivity = await prisma.activity.create({
data: {
type,
date: new Date(date),
duration,
caloriesBurned,
userId: parseInt(userId, 10),
},
});
res.status(201).json(newActivity);
} catch (error) {
console.error('Error creating activity:', error);
res.status(500).json({ message: 'Failed to create activity' });
}
});
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
});