-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (52 loc) · 1.43 KB
/
index.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
const express = require('express');
const app = express();
const dbClientPromise = require('./db');
const PORT = process.env.PORT || 5001;
app.use(express.json());
app.get('/users', async (req, res) => {
const db = await dbClientPromise;
const users = await db.collection('users').find().toArray();
res.json(users);
});
app.get('/users/:id', async (req, res) => {
const emailId = req.params.id;
const db = await dbClientPromise;
const user = await db.collection('users').findOne({
email: emailId.toLowerCase().trim()
}, { projection: { _id: 0 }});
res.json(user);
});
app.post('/users', async (req, res) => {
const db = await dbClientPromise;
const newUser = {
name: req.body.name,
email: req.body.email,
age: req.body.age
};
await db.collection('users').insertOne(newUser);
res.json({ status: 'ok' });
});
app.put('/users', async (req, res) => {
const email = req.body.email;
const newName = req.body.name;
const db = await dbClientPromise;
await db.collection('users').updateOne({
email
}, {
$set: {
name: newName
}
});
res.json({ status: 'ok' });
});
app.delete('/users/:id', async (req, res) => {
const emailId = req.params.id;
const db = await dbClientPromise;
await db.collection('users').deleteOne({
email: emailId.toLowerCase().trim()
});
res.json({ status: 'ok' });
});
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});