Created
March 7, 2016 05:15
-
-
Save wookiecooking/6550bac1d695a77fe6da to your computer and use it in GitHub Desktop.
express laziness
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = require('express')(); | |
var bodyParser = require('body-parser'); | |
var _ = require('lodash') | |
var mongoose = require('mongoose'); | |
var Schema = mongoose.Schema | |
mongoose.connect('mongodb://127.0.0.1:27017/test'); | |
var CatSchema = new Schema({ | |
name: String, | |
simple: String, | |
yo: String | |
}) | |
var Cat = mongoose.model('cat', CatSchema); | |
var validationMiddleware = { | |
creation: (req, res, next) => { next() }, | |
update: (req, res, next) => { next() } | |
} | |
app.use(bodyParser.urlencoded({ extended: false })) | |
app.use(bodyParser.json()) | |
app.get('/:model', (req, res){}=> { | |
mongoose.models[req.params.model].find({}, (err, records) => { | |
if (err || !records ) { console.log(err); return res.send('error'); } | |
res.json(records) | |
}) | |
}) | |
app.get('/:model/:id', (req, res) => { | |
mongoose.models[req.params.model].findById(req.params.id, function (err, entity) { | |
if (err || !entity ) { console.log(err); return res.send('error'); } | |
res.json(entity) | |
}); | |
}); | |
app.post('/:model', validationMiddleware.creation, (req, res) => { | |
mongoose.models[req.params.model].findOne(req.body, (err, existing) => { | |
if (err || !existing ) { console.log(err); return res.send('error'); }} | |
if (existing) { cb(existing, null) }; | |
var item = new mongoose.models[req.params.model](req.body); | |
item.save( err => { res.json(item) }); | |
}); | |
}) | |
app.post('/:model/:id', validationMiddleware.update, (req, res)=> { | |
if(req.body._id) { delete req.body._id; }; | |
mongoose.models[req.params.model].findById(id, function (err, entity) { | |
if (err || !entity ) { console.log(err); return res.send('error'); }} | |
_.extend(entity, req.body); | |
entity.save(function (err) { | |
if (err) { console.log(err); return res.send('error'); }} | |
res.json(entity) | |
}); | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment