Skip to content

Instantly share code, notes, and snippets.

@jcarroyo
Created February 8, 2016 00:35
Show Gist options
  • Save jcarroyo/d1e240c7282ae829587f to your computer and use it in GitHub Desktop.
Save jcarroyo/d1e240c7282ae829587f to your computer and use it in GitHub Desktop.
Memory REST API
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var uuid = require('uuid');
var students = [];
// parse application/json
app.use(bodyParser.json());
app.get('/students', function(req, res){
res.json(students);
});
app.post('/students', function(req, res){
var id = uuid.v4();
var student = req.body;
student.id = id;
students.push(student);
res.status(201).send(student);
});
app.delete('/students/:id', function(req, res){
var student = getStudentByID(req.params.id);
if(student){
students.splice(students.indexOf(student), 1);
return res.send("ok");
}
return res.send("");
});
app.put('/students/:id', function(req, res){
var student = getStudentByID(req.params.id);
if(student){
var id = req.params.id;
for(var key in req.body){
student[key] = req.body[key];
}
student.id = id;
return res.send("OK");
}
return res.send("");
});
app.get('/students/:id', function(req, res){
var student = getStudentByID(req.params.id);
if(student){
res.json(student);
}else{
res.json({});
}
});
function getStudentByID(id){
var student = students.filter(function(s){
return s.id == id;
});
return student? student[0] : null;
}
app.listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment