Add sessions endpoints with queries
This commit is contained in:
39
services/sessions/sessionsModel.js
Normal file
39
services/sessions/sessionsModel.js
Normal file
@@ -0,0 +1,39 @@
|
||||
const db = require('../../data/dbConfig');
|
||||
|
||||
module.exports = {
|
||||
addSession,
|
||||
findUserSessions,
|
||||
updateSession,
|
||||
removeSession
|
||||
};
|
||||
|
||||
async function addSession(session) {
|
||||
const [id] = await db('sessions')
|
||||
.insert(session);
|
||||
return findSessionById(id);
|
||||
}
|
||||
|
||||
function findUserSessions(user_id) {
|
||||
return db
|
||||
.from("sessions")
|
||||
.where({ user_id });
|
||||
}
|
||||
|
||||
function findSessionById(id) {
|
||||
return db('sessions')
|
||||
.where({ id })
|
||||
.first();
|
||||
}
|
||||
|
||||
async function updateSession(id, changes) {
|
||||
await db('sessions')
|
||||
.where({ id })
|
||||
.update(changes, '*');
|
||||
return findSessionById(id);
|
||||
}
|
||||
|
||||
async function removeSession(id) {
|
||||
await db('sessions')
|
||||
.where({ id })
|
||||
.del();
|
||||
}
|
||||
43
services/sessions/sessionsRouter.js
Normal file
43
services/sessions/sessionsRouter.js
Normal file
@@ -0,0 +1,43 @@
|
||||
const router = require('express').Router();
|
||||
|
||||
const { authenticate } = require('../auth/authenticate');
|
||||
const Sessions = require('../sessions/sessionsModel');
|
||||
|
||||
router.post('/sessions', authenticate, (req, res) => {
|
||||
Sessions.addSession(req.body)
|
||||
.then(response => {
|
||||
res.status(200).json(response);
|
||||
})
|
||||
.catch(err => res.send(err));
|
||||
});
|
||||
|
||||
router.get('/:id/sessions', authenticate, (req, res) => {
|
||||
Sessions.findUserSessions(req.params.id)
|
||||
.then(users => {
|
||||
res.status(200).json(users);
|
||||
})
|
||||
.catch(err => res.send(err));
|
||||
});
|
||||
|
||||
router.put('/sessions/:id', authenticate, async (req, res) => {
|
||||
Sessions.updateSession(req.params.id, req.body)
|
||||
.then(session => {
|
||||
if (session) {
|
||||
res.status(200).json(session);
|
||||
} else {
|
||||
res.status(404).json({ message: 'The session could not be found' });
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
res.status(500).json(err);
|
||||
});
|
||||
});
|
||||
|
||||
router.delete("/sessions/:id", authenticate, async (req, res) => {
|
||||
Sessions.removeSession(req.params.id)
|
||||
.then(() => res.status(200).json({ message: 'The session has been successfully deleted' }))
|
||||
.catch(err => res.json(err));
|
||||
});
|
||||
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user