Skip to content

Instantly share code, notes, and snippets.

@EnoF
Created February 27, 2014 19:08
Show Gist options
  • Save EnoF/9256893 to your computer and use it in GitHub Desktop.
Save EnoF/9256893 to your computer and use it in GitHub Desktop.
express.js example
'use strict';
var express = require('express');
var mongoskin = require('mongoskin');
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(allowCrossDomain);
});
var db = mongoskin.db('localhost:13337/portfolio', { safe: true});
app.param('collection', function(req, res, next, collection){
req.collection = db.collection(collection);
return next();
});
app.get('/', function(req, res){
res.send('Nothing to see here...');
});
app.get('/:collection/', function(req, res){
req.collection.find().toArray(function(err, projects){
res.send(projects);
});
});
app.get('/:collection/:id', function(req, res){
req.collection.findById(req.params.id,
function(e, result){
if (e) return next(e);
res.send(result);
});
});
app.post('/:collection/', function(req, res){
req.collection.insert(req.body, {}, function(e, results){
if(e) return next(e);
res.send(results[0]);
});
});
app.put('/:collection/:id', function(req, res){
delete req.body._id;
req.collection.updateById(req.params.id, {
$set:req.body
}, {
safe:true,
multi:false
}, function(e, result){
if (e) return next(e)
res.send((result===1)?{msg:'success'}:{msg:'error'})
})
});
app.del('/:collection/:id', function(req, res){
req.collection.removeById(req.params.id,
function(e, result){
if (e) return next(e);
res.send((result===1)?{msg:'success'}:{msg:'error'});
});
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment