-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
110 lines (89 loc) · 2.88 KB
/
app.js
File metadata and controls
110 lines (89 loc) · 2.88 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
const express = require('express')
const {MongoClient} = require('mongodb')
const fetch = require('node-fetch')
const app = express()
const PORT = 3000
const mongoUri = 'mongodb://127.0.0.1:27017'
const dbName = 'jsonPlaceholderDB'
app.use(express.json())
let db
let usersCollection, postsCollection, commentsCollection
async function connectDB() {
const client = new MongoClient(mongoUri)
await client.connect()
db = client.db(dbName)
usersCollection = db.collection('users')
postsCollection = db.collection('posts')
commentsCollection = db.collection('comments')
}
async function loadJSONPlaceholderData() {
const [users, posts, comments] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()),
fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json()),
fetch('https://jsonplaceholder.typicode.com/comments').then(res =>
res.json(),
),
])
await usersCollection.deleteMany({})
await postsCollection.deleteMany({})
await commentsCollection.deleteMany({})
await usersCollection.insertMany(users.slice(0, 10))
await postsCollection.insertMany(posts)
await commentsCollection.insertMany(comments)
}
// GET /load
app.get('/load', async (req, res) => {
try {
await loadJSONPlaceholderData()
res.sendStatus(200)
} catch (err) {
res.status(500).send('Failed to load data')
}
})
// DELETE /users
app.delete('/users', async (req, res) => {
await usersCollection.deleteMany({})
res.send('All users deleted')
})
// DELETE /users/:userId
app.delete('/users/:userId', async (req, res) => {
const userId = parseInt(req.params.userId)
await usersCollection.deleteOne({id: userId})
res.send(`User ${userId} deleted`)
})
// GET /users/:userId
app.get('/users/:userId', async (req, res) => {
const userId = parseInt(req.params.userId)
const user = await usersCollection.findOne({id: userId})
if (!user) return res.status(404).send('User not found')
const userPosts = await postsCollection.find({userId}).toArray()
const allComments = await commentsCollection.find().toArray()
const postsWithComments = userPosts.map(post => ({
...post,
comments: allComments.filter(c => c.postId === post.id),
}))
res.json({user, posts: postsWithComments})
})
// PUT /users
app.put('/users', async (req, res) => {
const newUser = req.body
if (!newUser || !newUser.id) {
return res.status(400).send('Invalid user data')
}
const existing = await usersCollection.findOne({id: newUser.id})
if (existing) {
return res.status(400).send('User already exists')
}
await usersCollection.insertOne(newUser)
res.status(201).send('User added')
})
// Connect to DB and start server
connectDB()
.then(() => {
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`)
})
})
.catch(err => {
console.error('Failed to connect to DB:', err)
})