Add users endpoints with queries

This commit is contained in:
ruihildt 2019-08-01 09:42:25 +02:00
parent d97221e522
commit ccc7a0bfb0
5 changed files with 67 additions and 0 deletions

17
.eslintrc.js Normal file
View File

@ -0,0 +1,17 @@
module.exports = {
"env": {
"commonjs": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
}
};

View File

@ -53,6 +53,7 @@ Sleep Tracker is intended for anyone interested in improving their sleep and hea
- `GET /api/users/:id` - fetch a user - `GET /api/users/:id` - fetch a user
- `PUT /api/users/:id` - update a user - `PUT /api/users/:id` - update a user
- `DELETE /api/users/:id` - delete a user
- `GET /api/users/:id/sessions` - fetch list of all sessions by user id - `GET /api/users/:id/sessions` - fetch list of all sessions by user id
- `POST /api/users/:id/sessions` - add a session by user id - `POST /api/users/:id/sessions` - add a session by user id

View File

@ -3,6 +3,7 @@ const helmet = require('helmet');
const cors = require('cors'); const cors = require('cors');
const authRouter = require('../services/auth/authRouter'); const authRouter = require('../services/auth/authRouter');
const usersRouter = require('../services/users/usersRouter');
const server = express(); const server = express();
@ -11,5 +12,6 @@ server.use(express.json());
server.use(cors()); server.use(cors());
server.use('/api/auth', authRouter); server.use('/api/auth', authRouter);
server.use('/api/users', usersRouter);
module.exports = server; module.exports = server;

View File

@ -4,6 +4,8 @@ module.exports = {
add, add,
findBy, findBy,
findById, findById,
update,
remove
}; };
function findBy(filter) { function findBy(filter) {
@ -23,3 +25,16 @@ function findById(id) {
.first() .first()
.select('id', 'email', 'username'); .select('id', 'email', 'username');
} }
async function update(id, changes) {
await db('users')
.where({ id })
.update(changes, '*');
return findById(id);
}
function remove(id) {
return db('users')
.where({ id })
.del();
}

View File

@ -0,0 +1,32 @@
const router = require('express').Router();
const { authenticate } = require('../auth/authenticate');
const Users = require('../users/usersModel');
router.get('/:id', authenticate, (req, res) => {
Users.findById(req.params.id)
.then(users => {
res.status(200).json(users);
})
.catch(err => res.send(err));
});
router.put('/:id', authenticate, async (req, res) => {
Users.update(req.params.id, req.body)
.then( user => {
if (user) {
res.status(200).json(user);
} else {
res.status(404).json({ message: 'The user could not be found' });
}
})
.catch(err => res.status(500).json({ message: 'Error updating the user' }));
});
router.delete("/:id", (req, res) => {
Users.remove(req.params.id)
.then(data => res.status(200).json(data))
.catch(err => res.json(err));
});
module.exports = router;