Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions controllers/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const users = require('../data/index');
const sampleUser = require('../data/sampleUser');

// Should retrieve the entire array from _data/index_

const listUsers = (req, res) => {
res.json(users)
}

// Should retrieve just the user that matches the passed-in id
const showUser = (req, res) => {
let id = req.params.id -1
if (users[id]){
return res.json(users[id])
} else {
res.status(404).send({ msg: `User with the ID of ${req.params.id} not found!` })
}
}

// Should add a user to the array
const createUser = (req, res) => {
let counter = users.length
let newUser = sampleUser
newUser.id = counter + 1
users.push(newUser)
return res.json(users[counter])
}

// Should update one user in the array based on its id
const updateUser = (req, res) => {
let targetId = req.params.id -1
if (users[targetId]){
users[targetId].name = sampleUser.name
return res.json(users[targetId])
} else {
res.status(400).send({ msg: `User with the ID of ${req.params.id} not found!` })
}
}

// Should delete one user from the array based on its id
const deleteUser = (req, res) => {
let targetId = req.params.id -1
if (users[targetId]){
users[targetId].isActive = false
res.send("Deleted")
} else {
res.status(400).send({ msg: `User with the ID of ${req.params.id} not found!` })
}
}

module.exports = {
listUsers,
showUser,
createUser,
updateUser,
deleteUser
};
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = process.env.PORT || 4000
const users = require('./routes/users')

app.get('/', (req, res) => res.send('default route'))

app.use(bodyParser.json())
app.use(users)

app.listen(port, () => {
console.log('app is listening on:', port)
})
41 changes: 30 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions routes/users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const express = require('express');
const controller = require('../controllers/users');
const router = express.Router();

router.get('/users', controller.listUsers)
router.get('/users/:id', controller.showUser)
router.post('/users', controller.createUser)
router.put('/users/:id', controller.updateUser)
router.delete('/users/:id', controller.deleteUser)

module.exports = router;