Skip to content

Commit

Permalink
Added RESTful API example.
Browse files Browse the repository at this point in the history
  • Loading branch information
sayar committed Jul 28, 2015
1 parent 2e09c2e commit 5abd663
Show file tree
Hide file tree
Showing 5 changed files with 254 additions and 0 deletions.
141 changes: 141 additions & 0 deletions 12_AdvancedRESTAPI/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var http = require('http');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var api = require('./routes/api');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/api', api);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('Listening on ' + bind);
}
17 changes: 17 additions & 0 deletions 12_AdvancedRESTAPI/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "12_AdvancedRESTAPI",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./app.js"
},
"dependencies": {
"body-parser": "~1.13.2",
"cookie-parser": "~1.3.5",
"debug": "~2.2.0",
"express": "~4.13.1",
"jade": "~1.11.0",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0"
}
}
88 changes: 88 additions & 0 deletions 12_AdvancedRESTAPI/routes/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
var express = require('express');
var router = express.Router();

var dogs = [
{
"dog_id": "0",
"dog_name": "Ginger"
},
{
"dog_id": "1",
"dog_name": "Ruby"
},
{
"dog_id": "2",
"dog_name": "Buddy"
}
];

/* GET all dogs */
router.get('/dogs/', function(req, res, next) {
res.json(dogs);
});

/* PUT replace all dogs */
router.put('/dogs/', function(req, res, next) {
console.log(req.body);
dogs = req.body;
res.json({"STATUS": "200 OK"});
});

/* POST create a new dog */
router.post('/dogs/', function(req, res, next) {
dogs.push(req.body)
res.json({"STATUS": "200 OK"});
});

/* DELETE delete the entire dog collection */
router.delete('/dogs/', function(req, res, next) {
dogs = [];
res.json({"STATUS": "200 OK"});
});


/* GET a specific dog */
router.get('/dogs/:id', function(req, res, next) {
var i = 0;
var dog = null;
for(i = 0; i != dogs.length; i++){
if(dogs[i].dog_id == req.params.id){
dog = dogs[i];
break;
}
}
dog !== null ? res.json(dog) : res.json({"STATUS": "404 NOT FOUND"})
});

/* PUT replace a specific dog with another dog */
router.put('/dogs/:id', function(req, res, next) {
var i = 0;
var dog = null;
for(i = 0; i != dogs.length; i++){
if(dogs[i].dog_id == req.params.id){
dog = dogs[i];
break;
}
}
if(dog !== null){
dog.dog_name = req.body['dog_name']
res.json({"STATUS": "200 OK"});
} else {
res.json({"STATUS": "404 NOT FOUND"});
}
});

/* DELETE a specific dog from the collection */
router.delete('/dogs/:id', function(req, res, next) {
var i = 0;
for(i = 0; i != dogs.length; i++){
if(dogs[i].dog_id == req.params.id){
dogs.splice(i, 1);
return res.json({"STATUS": "200 OK"});
}
}
return res.json({"STATUS": "404 NOT FOUND"});
});


module.exports = router;
8 changes: 8 additions & 0 deletions 12_AdvancedRESTAPI/routes/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
res.send('Hello World!');
});

module.exports = router;
Binary file modified Presentations for Visual Studio Code MVA/02.Express.pptx
Binary file not shown.

0 comments on commit 5abd663

Please sign in to comment.