Skip to content

Instantly share code, notes, and snippets.

@WORMSS
Last active April 18, 2017 13:27
Show Gist options
  • Save WORMSS/d7ccad1d14441c3b07484540359ae127 to your computer and use it in GitHub Desktop.
Save WORMSS/d7ccad1d14441c3b07484540359ae127 to your computer and use it in GitHub Desktop.
micro-rest-api-server
// imports
const Express = require("express");
const bodyParser = require("body-parser");
// Some datastore to play with.
const bookDb = initDb();
// Set up express app.
const app = new Express();
// Express Routes.
app.get("/book", getBooks); // send all books.
app.route("/book/:id(\\d+)") // book with a numeric id
.get(getBook) // get a single book by id.
.post(bodyParser.json(), setBook) // store a single book by id. Parse body before hand.
.delete(deleteBook); // delete a single book by id.
// Starting Server. Console when server is ready.
app.listen(8080, () => console.log("Server Started"));
/**
* Behind the scenes functions.
*/
function getBooks(req, res) {
// Turn map into array, Inject BookId into objects.
let modifiedBooks = Array.from(bookDb.entries())
.map(([key, book]) => Object.assign({"_id": key}, book));
// Send modified array.
res.json(modifiedBooks);
}
function getBook(req, res) {
let bookId = parseInt(req.params.id); // Make sure db has the book needed.
if ( !bookDb.has(bookId) ) {
return res.status(404).end(); // if no book, send NOT FOUND.
}
res.json(bookDb.get(bookId)); // send book object.
}
function setBook(req, res) {
let bookId = parseInt(req.params.id);
let book = req.body;
// Make sure data coming in from outside is good.
// This is very crucial for security reasons.
// Not implemented for this demo.
let invalidReason = isInvalidBook(bookId, book);
if ( invalidReason ) {
return res.status(400).end(invalidReason); // if book is not valid, send BAD REQUEST, and reasons why.
}
// Store book in db.
bookDb.set(bookId, book);
res.send(); // Send acknowledgement.
}
function deleteBook(req, res) {
let bookId = parseInt(req.params.id);
// Make sure book exists in db.
if ( !bookDb.has(bookId) ) {
return res.status(404).end(); // If does not exist, send NOT FOUND.
}
// Delete book from db.
bookDb.delete(bookId);
}
function isBookInvalid(bookId, book) {
// test book object to see if it is invalid
// return reason why if it is invalid.
// if valid, return falsey.
return false;
}
function initDb() {
// Some seed data for demo.
return new Map([
[1, { "title": "Twisted Metal", "author": "Tony Ballantyne" }],
[2, { "title": "Blood and Iron", "author": "Tony Ballantyne" }]
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment