-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (65 loc) · 1.9 KB
/
server.js
File metadata and controls
78 lines (65 loc) · 1.9 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
const express = require('express');
const { MongoClient, ObjectId } = require('mongodb');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const DB_NAME = process.env.DB_NAME || 'userdb';
let db;
// Connect to MongoDB
async function connectToMongoDB() {
try {
const client = new MongoClient(MONGODB_URI);
await client.connect();
db = client.db(DB_NAME);
console.log('Connected to MongoDB successfully');
} catch (error) {
console.error('Failed to connect to MongoDB:', error);
process.exit(1);
}
}
// Middleware
app.use(express.json());
// GET endpoint for retrieving user by ID
app.get('/users/:id', async (req, res) => {
try {
const { id } = req.params;
// Validate ObjectId format
if (!ObjectId.isValid(id)) {
return res.status(400).json({
error: 'Invalid user ID format'
});
}
const usersCollection = db.collection('users');
// Query for user with matching _id and age > 21
const user = await usersCollection.findOne({
_id: new ObjectId(id),
age: { $gt: 21 }
});
if (!user) {
return res.status(404).json({
error: 'User not found or user is 21 or younger'
});
}
res.json(user);
} catch (error) {
console.error('Error retrieving user:', error);
res.status(500).json({
error: 'Internal server error'
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'OK', message: 'Server is running' });
});
// Start server
async function startServer() {
await connectToMongoDB();
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Health check: http://localhost:${PORT}/health`);
console.log(`User endpoint: http://localhost:${PORT}/users/:id`);
});
}
startServer();