Skip to content

Instantly share code, notes, and snippets.

@hillal20
Forked from luishrd/index.js
Last active May 3, 2018 18:52
Show Gist options
  • Save hillal20/ca217939f4b60576eeced662b517cde7 to your computer and use it in GitHub Desktop.
Save hillal20/ca217939f4b60576eeced662b517cde7 to your computer and use it in GitHub Desktop.
const express = require('express');
const helmet = require('helmet'); // 1 yarn add helment || npm i helmet // 2
// import db from './data/db';
const userRoutes = require('./users/userRoutes');
const server = express();
// client -> [error, m1, post, m3] -> [rh1, rh2]
function greeter(name) {
return function(req, res, next) {
console.log(`hello ${name}`);
console.log(req.query);
// http://localhost:8000/?pass=mellon
if (req.query.pass === 'mellon') {
next();
} else {
res.send('YOU SHALL NOT PASS!!!!');
}
};
}
function logger(msg) {
return function(req, res, next) {
console.log(`\n= ${msg}: ${req.url}`);
next();
};
}
function errorHandler(err, req, res, next) {
if (err) {
// check the type of error and react to it
if (err.errno === 19) {
res.status(400).json({ msg: 'Please provide all required fields' });
} else {
res.status(500).json({ error: 'something bad happened' });
}
}
}
// add middleware
// server.use(greeter('Lukasz'));
server.use(logger('loading'));
server.use(helmet()); // 3
server.use(express.json());
// user route handlers
server.use('/api/users', userRoutes);
server.get('/', (req, res) => {
res.json({ api: 'running' });
});
server.use(errorHandler);
const port = 8000;
server.listen(port, () => console.log(`\n== API Running on port ${port} ==\n`));
Raw
// --------router---------
userRoutes
const express = require('express');
const db = require('../data/db');
const router = express.Router();
// only cares about urls beginning with: /api/users
router.post('/', (req, res, next) => {
const userInformation = req.body;
console.log('user information', userInformation);
db
.insert(userInformation)
.then(response => {
res.status(201).json(response);
})
.catch(err => {
console.log(err);
logErrorToDatabase(err);
next(err);
});
// .catch(err => {
// if (err.errno === 19) {
// res.status(400).json({ msg: 'Please provide all required fields' });
// } else {
// res.status(500).json({ erro: err });
// }
// });
});
// http://foo.com?search=bar&sort=asc
// req.query === { search: 'bar', sort: 'asc' }
// http://localhost:5000?id=1 // just to use req.query
// write it using an URL parameter instead /:id
router.delete('/', function(req, res) {
const { id } = req.query;
let user;
db
.findById(id)
.then(foundUser => {
user = { ...foundUser[0] };
db.remove(id).then(response => {
res.status(200).json(user);
});
})
.catch(err => {
res.status(500).json({ erro: err });
});
});
router.put('/:id', function(req, res) {
const { id } = req.params;
const update = req.body;
db
.update(id, update)
.then(count => {
if (count > 0) {
db.findById(id).then(users => {
res.status(200).json(users[0]);
});
} else {
res.status(404).json({ msg: 'user not found' });
}
})
.catch(err => {
res.status(500).json(err);
});
});
router.get('/', (req, res) => {
//get the users
db
.find()
.then(users => {
res.json(users);
})
.catch(err => {
res.status(500).json({ error: err });
// do something with the error
});
});
// /123
router.get('/:id', (req, res) => {
// grab the id from URL parameters
const id = req.params.id;
db
.findById(id)
.then(users => {
if (users.length === 0) {
res.status(404).json({ message: 'user not found' });
} else {
res.json(users[0]);
}
})
.catch(err => {
// do something with the error
res.status(500).json({ error: err });
});
});
module.exports = router;
//// . -----middleware------
// inside the middleware folder
module.exports = {
greeter,
logger,
errorHandler,
};
function greeter(name) {
return function(req, res, next) {
console.log(`hello ${name}`);
console.log(req.query);
// http://localhost:8000/?pass=mellon
if (req.query.pass === 'mellon') {
next();
} else {
res.send('YOU SHALL NOT PASS!!!!');
}
};
}
function logger(msg) {
return function(req, res, next) {
console.log(`\n= ${msg || 'requesting'}: ${req.url}`);
next();
};
}
function errorHandler(err, req, res, next) {
if (err) {
// check the type of error and react to it
if (err.errno === 19) {
res.status(400).json({ msg: 'Please provide all required fields' });
} else {
res.status(500).json({ error: 'something bad happened' });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment