-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
128 lines (104 loc) · 3.26 KB
/
Copy pathindex.js
File metadata and controls
128 lines (104 loc) · 3.26 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
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const crypto = require('crypto'); // Built-in Node.js module for generating IDs
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
// In-memory "database"
let users = [];
let exercises = [];
// Helper function to generate a unique ID
const generateId = () => crypto.randomBytes(12).toString('hex');
// 1. POST to /api/users to create a new user.
app.post('/api/users', (req, res) => {
const username = req.body.username;
if (!username) {
return res.status(400).json({ error: 'Username is required' });
}
const newUser = {
username: username,
_id: generateId()
};
users.push(newUser);
res.json(newUser);
});
// 2. GET to /api/users to get a list of all users.
app.get('/api/users', (req, res) => {
res.json(users);
});
// 3. POST to /api/users/:_id/exercises to add an exercise.
app.post('/api/users/:_id/exercises', (req, res) => {
const userId = req.params._id;
const { description, duration, date } = req.body;
// Find the user by their ID
const user = users.find(u => u._id === userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Validate required fields
if (!description || !duration) {
return res.status(400).json({ error: 'Description and duration are required' });
}
// Create the exercise object
const exerciseDate = date ? new Date(date) : new Date();
const newExercise = {
userId: user._id,
username: user.username,
description: description,
duration: parseInt(duration),
date: exerciseDate
};
exercises.push(newExercise);
// Return the user object with the exercise fields added
res.json({
_id: user._id,
username: user.username,
date: newExercise.date.toDateString(),
duration: newExercise.duration,
description: newExercise.description
});
});
// 4. GET to /api/users/:_id/logs to retrieve a user's exercise log.
app.get('/api/users/:_id/logs', (req, res) => {
const userId = req.params._id;
const { from, to, limit } = req.query;
const user = users.find(u => u._id === userId);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Get all exercises for this user
let userExercises = exercises.filter(ex => ex.userId === userId);
// Apply filters if they exist
if (from) {
const fromDate = new Date(from);
userExercises = userExercises.filter(ex => ex.date >= fromDate);
}
if (to) {
const toDate = new Date(to);
userExercises = userExercises.filter(ex => ex.date <= toDate);
}
if (limit) {
userExercises = userExercises.slice(0, parseInt(limit));
}
// Format the log array as required
const log = userExercises.map(ex => ({
description: ex.description,
duration: ex.duration,
date: ex.date.toDateString()
}));
// Construct the final response object
res.json({
_id: user._id,
username: user.username,
count: log.length,
log: log
});
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port);
});