From 49e1bcaa5c87b41fc47834bd06e35c0871eee294 Mon Sep 17 00:00:00 2001 From: Ethan Ho Date: Fri, 1 Dec 2023 15:42:35 -0800 Subject: [PATCH] Finished backend routes Co-authored-by: cherhchen --- app.js | 4 ++++ routes/users.js | 37 +++++++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/app.js b/app.js index 18fd6c7..641de4c 100644 --- a/app.js +++ b/app.js @@ -3,6 +3,9 @@ const cors = require('cors'); require('dotenv').config(); +// routes +const users = require('./routes/users'); + const app = express(); const PORT = process.env.PORT || 3001; @@ -15,6 +18,7 @@ app.use( // add all routes under here app.use(express.json()); // for req.body +app.use('/users', users); app.listen(PORT, () => { console.log(`Server listening on ${PORT}`); diff --git a/routes/users.js b/routes/users.js index 96434be..6826366 100644 --- a/routes/users.js +++ b/routes/users.js @@ -9,43 +9,60 @@ userRouter.get('/', async (req, res) => { const allUsers = await db.query(`SELECT * FROM users;`); res.status(200).json(keysToCamel(allUsers)); } catch (err) { - console.log(err); res.status(500).send(err.message); } }); - userRouter.get('/pending-accounts', async (req, res) => { try { const pendingAccounts = await db.query(`SELECT * FROM users WHERE approved = FALSE;`); res.status(200).json(keysToCamel(pendingAccounts)); } catch (err) { - console.log(err); res.status(500).send(err.message); } }); - userRouter.post('/', async (req, res) => { try { - const { id, email, type, approved } = req.params; + const { id, email, type, approved } = req.body; + await db.query(`INSERT INTO users (id, email, "type", approved) VALUES ($1, $2, $3, $4);`, [ + id, + email, + type, + approved, + ]); + res.status(201).json({ + status: 'Success', + }); } catch (err) { - + res.status(500).json({ + status: 'Failed', + msg: err.message, + }); } }); userRouter.put('/:uid', async (req, res) => { try { - + const { uid } = req.params; + const updatedApproval = await db.query( + `UPDATE users SET approved = TRUE WHERE id = $1 RETURNING *;`, + [uid], + ); + return res.status(200).send(updatedApproval[0]); } catch (err) { - + return res.status(500).send(err.message); } }); userRouter.delete('/:uid', async (req, res) => { try { - + const { uid } = req.params; + await db.query(`DELETE FROM users WHERE id = $1;`, [uid]); + res.status(200).send('Deleted user'); } catch (err) { - + res.status(500).send(err.message); } }); + +module.exports = userRouter;