Skip to content

Instantly share code, notes, and snippets.

@ryan-hamblin
Created December 20, 2018 15:32
Show Gist options
  • Save ryan-hamblin/f112a8e2f7656ae02bd47cb1fc819b41 to your computer and use it in GitHub Desktop.
Save ryan-hamblin/f112a8e2f7656ae02bd47cb1fc819b41 to your computer and use it in GitHub Desktop.
A very basic crud server, w/out persistence. For practice and example only.
const express = require('express');
const port = 5000;
const server = express();
server.use(express.json());
// write custom middleware.
function logger(req, res, next) {
console.log(
`[${new Date().toISOString()}] ${req.method} to ${req.url} ${req.get(
'Origin'
)}`
);
next();
}
function atGate(req, res, next) {
console.log('At the gate, about to be eaten');
next();
}
function auth(req, res, next) {
if (req.url === '/mellon') {
next();
} else {
res.send('You shall not pass!');
}
}
server.use(logger);
server.use(atGate);
server.get('/mellon', auth, (req, res) => {
console.log('Gate opening... ');
console.log('Inside and safe!');
res.send('Welcome Traveler!');
});
server.get('/hobbits', (req, res) => {
// query string parameters get added to req.query
const sortField = req.query.sortby || 'id';
const hobbits = [
{
id: 1,
name: 'Samwise Gamgee'
},
{
id: 3,
name: 'Bilbo Baggins'
},
{
id: 2,
name: 'Frodo Baggins'
}
];
// apply the sorting
const response = hobbits.sort((a, b) =>
a[sortField] < b[sortField] ? -1 : 1
);
res.status(200).json(response);
}); // READ data
let hobbits = [
{
id: 1,
name: 'Bilbo Baggins',
age: 111
},
{
id: 2,
name: 'Frodo Baggins',
age: 33
}
];
let nextId = 3;
// and modify the post endpoint like so:
server.post('/hobbits', (req, res) => {
const hobbit = req.body;
hobbit.id = nextId++;
hobbits.push(hobbit);
res.status(201).json(hobbits);
}); // CREATE data
server.put('/hobbits', (req, res) => {
res.status(200).json({ url: '/hobbits', operation: 'PUT' });
}); // UPDATE data
server.delete('/hobbits/:id', (req, res) => {
const id = req.params.id;
// or we could destructure it like so: const { id } = req.params;
res.status(200).json({
url: `/hobbits/${id}`,
operation: `DELETE for hobbit with id ${id}`
});
}); // DESTROYING/DELETING data
server.use(function(req, res) {
res.status(404).send(`Ain't nobody got time for dat!`);
});
server.listen(port, () => {
console.log(`server listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment