/** * Expose `ModelRoute`. */ module.exports = ModelRoute; /** * Module dependencies. */ var Route = require('route') , debug = require('debug')('collection') , util = require('util') , inherits = util.inherits , assert = require('assert'); /** * Create a new `ModelRoute` with the given `options`. * * @param {Object} options * @return {ModelRoute} */ function ModelRoute(options) { Route.apply(this, arguments); this.options = options; // model this.model = this.dependencies.model.schema; // setup http routes this.setupRoutes(this.app); debug('created with options', options); } /** * Inherit from `Route`. */ inherits(ModelRoute, Route); /** * Dependencies. */ ModelRoute.dependencies = { 'model': 'model' } ModelRoute.prototype.setupRoutes = function (app) { var Model = this.model; var ctx; var collection = this; app.use(function (req, res, next) { ctx = collection.createContext(req, res, next); ctx.emit('request', function () { ctx.emit(req.method.toLowerCase(), function () { next(); }); }); }); // create app.post('/', create); app.post('/new', create); function create(req, res, next) { ctx.emit('create', function (done) { Model.create(req.body, done); }); } // read app.get('/:id', query); app.get('/', query); function query(req, res, next) { var query = req.query; query.where = query.where || {}; if(req.param('id')) { query.where.id = req.param('id'); } if(query.where.id) { query.limit = 1; } if(query.limit) query.limit = Number(query.limit); if(query.skip) query.skip = Number(query.skip); ctx.emit('query', query, function (done) { Model.all(query, done); }); } // update app.put('/:id', function (req, res) { var body = req.body || {}; var id = req.param('id'); if(Number(id) == id) { id = Number(id); } ctx.emit('find', function () { Model.find(id, function (err, m) { if(err) { ctx.done(err); } else { ctx.emit('validate', body, function () { ctx.emit('update', body, function (done) { m.updateAttributes(body, done); }); }); } }); }); }); // delete app.del('/:id', function () { var id = req.param('id'); ctx.emit('delete', id, function (done) { Model.destroy(id, done); }); }); }