Add sessions endpoints with queries

This commit is contained in:
ruihildt 2019-08-01 16:25:44 +02:00
parent ccc7a0bfb0
commit 03a9c793d8
12 changed files with 167 additions and 36 deletions

2
.gitignore vendored
View File

@ -64,5 +64,5 @@ typings/
.vscode .vscode
# Databases # Databases
data/sleep-tracker.db3 # data/sleep-tracker.db3
data/test.db3 data/test.db3

View File

@ -48,17 +48,16 @@ Sleep Tracker is intended for anyone interested in improving their sleep and hea
## API Endpoints ## API Endpoints
- `POST /api/auth/register` - add a new user - [x] `POST /api/auth/register` - add a new user
- `POST /api/auth/login` - login with user/password - [x] `POST /api/auth/login` - login with user/password
- `GET /api/users/:id` - fetch a user - [x] `GET /api/users/:id` - fetch a user
- `PUT /api/users/:id` - update a user - [x] `PUT /api/users/:id` - update a user
- `DELETE /api/users/:id` - delete a user - [x] `DELETE /api/users/:id` - delete a user
- `GET /api/users/:id/sessions` - fetch list of all sessions by user id - [x] `GET /api/users/:id/sessions` - fetch list of all sessions by user id
- `POST /api/users/:id/sessions` - add a session by user id - [x] `POST /api/users/sessions` - add a session
- `GET /api/users/:id/sessions/:id` - fetch a single session by id - [x] `PUT /api/users/sessions/:id` - update a session by id
- `PUT /api/users/:id/sessions/:id` - update a session by id - [x] `DELETE /api/users/sessions/:id` - delete a session by id
- `DELETE /api/users/:id/sessions/:id` - delete a session by id
- `GET /api/dailyaverages/:id` - fetch a list of last 30 daily averages by user id - [ ] `GET /api/dailyaverages/:id` - fetch a list of last 30 daily averages by user id

View File

@ -4,6 +4,7 @@ const cors = require('cors');
const authRouter = require('../services/auth/authRouter'); const authRouter = require('../services/auth/authRouter');
const usersRouter = require('../services/users/usersRouter'); const usersRouter = require('../services/users/usersRouter');
const sessionsRouter = require('../services/sessions/sessionsRouter');
const server = express(); const server = express();
@ -13,5 +14,6 @@ server.use(cors());
server.use('/api/auth', authRouter); server.use('/api/auth', authRouter);
server.use('/api/users', usersRouter); server.use('/api/users', usersRouter);
server.use('/api/users', sessionsRouter);
module.exports = server; module.exports = server;

View File

@ -34,10 +34,13 @@ exports.up = function(knex) {
tbl tbl
.datetime('wake_time'); .datetime('wake_time');
tbl tbl
.integer('bed_tiredness') .integer('wake_mood')
.unsigned(); .unsigned();
tbl tbl
.integer('wake_mood') .integer('day_mood')
.unsigned();
tbl
.integer('bed_tiredness')
.unsigned(); .unsigned();
}) })
@ -45,16 +48,17 @@ exports.up = function(knex) {
tbl tbl
.increments(); .increments();
tbl tbl
.integer('session_user') .integer('session_id')
.unsigned() .unsigned()
.notNullable() .notNullable()
.references('sessions.user_id') .references('sessions.id')
.onUpdate('CASCADE') .onUpdate('CASCADE')
.onDelete('CASCADE'); .onDelete('CASCADE');
tbl tbl
.datetime('session_date') .integer('user_id')
.unsigned()
.notNullable() .notNullable()
.references('sessions.wake_time') .references('users.id')
.onUpdate('CASCADE') .onUpdate('CASCADE')
.onDelete('CASCADE'); .onDelete('CASCADE');
tbl tbl

View File

@ -0,0 +1,19 @@
exports.seed = function(knex) {
return knex('users').truncate()
.then(function () {
return knex('users').insert([
// {
// id: 1,
// email: 'gabe@ls.com',
// username: 'gabe',
// password: '1234'
// },
// {
// id: 2,
// email: 'gabe2@ls.com',
// username: 'gabe2',
// password: '1234'
// }
]);
});
};

View File

@ -0,0 +1,25 @@
exports.seed = function(knex) {
return knex('sessions').truncate()
.then(function () {
return knex('sessions').insert([
{
"id": 1,
"user_id": 1,
"bed_time": "",
"wake_time": "",
"wake_mood": 3,
"day_mood": 3,
"bed_tiredness": 3
},
{
"id": 2,
"user_id": 1,
"bed_time": "",
"wake_time": "",
"wake_mood": 4,
"day_mood": 4,
"bed_tiredness": 4
}
]);
});
};

BIN
data/sleep-tracker.db3 Normal file

Binary file not shown.

View File

@ -9,7 +9,7 @@ router.post('/register', (req, res) => {
const hash = bcrypt.hashSync(user.password, 10); const hash = bcrypt.hashSync(user.password, 10);
user.password = hash; user.password = hash;
Users.add(user) Users.addUser(user)
.then(saved => { .then(saved => {
res.status(201).json(saved); res.status(201).json(saved);
}) })
@ -21,7 +21,7 @@ router.post('/register', (req, res) => {
router.post('/login', (req, res) => { router.post('/login', (req, res) => {
let { username, password } = req.body; let { username, password } = req.body;
Users.findBy({ username }) Users.findUserBy({ username })
.first() .first()
.then(user => { .then(user => {
if (user && bcrypt.compareSync(password, user.password)) { if (user && bcrypt.compareSync(password, user.password)) {

View 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();
}

View 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;

View File

@ -1,39 +1,39 @@
const db = require('../../data/dbConfig'); const db = require('../../data/dbConfig');
module.exports = { module.exports = {
add, addUser,
findBy, findUserBy,
findById, findUserById,
update, updateUser,
remove removeUser
}; };
function findBy(filter) { function findUserBy(filter) {
return db('users') return db('users')
.where(filter); .where(filter);
} }
async function add(user) { async function addUser(user) {
const [id] = await db('users') const [id] = await db('users')
.insert(user); .insert(user);
return findById(id); return findUserById(id);
} }
function findById(id) { function findUserById(id) {
return db('users') return db('users')
.where({ id }) .where({ id })
.first() .first()
.select('id', 'email', 'username'); .select('id', 'email', 'username');
} }
async function update(id, changes) { async function updateUser(id, changes) {
await db('users') await db('users')
.where({ id }) .where({ id })
.update(changes, '*'); .update(changes, '*');
return findById(id); return findUserById(id);
} }
function remove(id) { function removeUser(id) {
return db('users') return db('users')
.where({ id }) .where({ id })
.del(); .del();

View File

@ -4,7 +4,7 @@ const { authenticate } = require('../auth/authenticate');
const Users = require('../users/usersModel'); const Users = require('../users/usersModel');
router.get('/:id', authenticate, (req, res) => { router.get('/:id', authenticate, (req, res) => {
Users.findById(req.params.id) Users.findUserById(req.params.id)
.then(users => { .then(users => {
res.status(200).json(users); res.status(200).json(users);
}) })
@ -12,8 +12,8 @@ router.get('/:id', authenticate, (req, res) => {
}); });
router.put('/:id', authenticate, async (req, res) => { router.put('/:id', authenticate, async (req, res) => {
Users.update(req.params.id, req.body) Users.updateUser(req.params.id, req.body)
.then( user => { .then(user => {
if (user) { if (user) {
res.status(200).json(user); res.status(200).json(user);
} else { } else {
@ -24,7 +24,7 @@ router.put('/:id', authenticate, async (req, res) => {
}); });
router.delete("/:id", (req, res) => { router.delete("/:id", (req, res) => {
Users.remove(req.params.id) Users.removeUser(req.params.id)
.then(data => res.status(200).json(data)) .then(data => res.status(200).json(data))
.catch(err => res.json(err)); .catch(err => res.json(err));
}); });