-
Notifications
You must be signed in to change notification settings - Fork 0
/
userRoutes.js
70 lines (62 loc) · 1.77 KB
/
userRoutes.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
import express from 'express';
const router = express.Router ();
import {db} from './firebase.js';
import {ref, set, get, update, remove} from 'firebase/database';
import verifyToken from './middlewares/verifyToken.js';
router.get ('/data', verifyToken, async (req, res, next) => {
const {userId} = req.body;
try {
get (ref (db, 'users/' + userId )).then (snapshot => {
if (snapshot.exists ()) {
res.status (200).json (snapshot.val ());
} else {
console.log ('No data available');
res.status(200).json({});
}
});
} catch (error) {
next (new Error (error.message));
}
});
router.post ('/data', verifyToken, async (req, res, next) => {
const {userId, userData} = req.body;
try {
await set (ref (db, 'users/' + userId + '/' + userData.id), userData)
.then (() => {
res.status (200).json ({...userData});
})
.catch (e => {
throw e;
});
} catch (error) {
next (new Error (error.message));
}
});
router.put('/data', verifyToken, async (req, res, next) => {
const { userId, updatedData } = req.body;
try {
await update(ref(db, `users/${userId}/${updatedData.id}`), updatedData)
.then(() => {
res.status(200).json({...updatedData});
})
.catch(e => {
throw e;
});
} catch (error) {
next(new Error(error.message));
}
});
router.delete('/data', verifyToken, async (req, res, next) => {
const { userId, items } = req.body;
console.log(items)
try {
for (const item of items) {
const itemRef = ref(db, `users/${userId}/${item.id}`);
await remove(itemRef)
}
res.status(200).json({ message: 'Items deleted successfully' });
} catch (error) {
next(new Error(error.message));
}
});
export default router;