loopback/node_modules/model-route/lib/model-route.js

132 lines
2.5 KiB
JavaScript
Raw Normal View History

2013-04-09 18:33:29 +00:00
/**
2013-04-18 00:43:00 +00:00
* Expose `ModelRoute`.
2013-04-09 18:33:29 +00:00
*/
2013-04-18 00:43:00 +00:00
module.exports = ModelRoute;
2013-04-09 18:33:29 +00:00
/**
* Module dependencies.
*/
2013-04-18 00:43:00 +00:00
var Route = require('route')
2013-04-09 18:33:29 +00:00
, debug = require('debug')('collection')
, util = require('util')
, inherits = util.inherits
, assert = require('assert');
/**
2013-04-18 00:43:00 +00:00
* Create a new `ModelRoute` with the given `options`.
2013-04-09 18:33:29 +00:00
*
* @param {Object} options
2013-04-18 00:43:00 +00:00
* @return {ModelRoute}
2013-04-09 18:33:29 +00:00
*/
2013-04-18 00:43:00 +00:00
function ModelRoute(options) {
Route.apply(this, arguments);
2013-04-09 18:33:29 +00:00
this.options = options;
// model
this.model = this.dependencies.model.schema;
2013-04-09 18:33:29 +00:00
// setup http routes
this.setupRoutes(this.app);
2013-04-09 18:33:29 +00:00
debug('created with options', options);
}
/**
2013-04-18 00:43:00 +00:00
* Inherit from `Route`.
2013-04-09 18:33:29 +00:00
*/
2013-04-18 00:43:00 +00:00
inherits(ModelRoute, Route);
2013-04-09 18:33:29 +00:00
/**
* Dependencies.
*/
2013-04-18 00:43:00 +00:00
ModelRoute.dependencies = {
'model': 'model'
2013-04-09 18:33:29 +00:00
}
2013-04-18 00:43:00 +00:00
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();
});
});
});
2013-04-09 18:33:29 +00:00
// create
app.post('/', create);
app.post('/new', create);
function create(req, res, next) {
ctx.emit('create', function (done) {
Model.create(req.body, done);
2013-04-09 18:33:29 +00:00
});
}
// 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);
2013-04-09 18:33:29 +00:00
});
}
// 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);
});
});
}
});
2013-04-09 18:33:29 +00:00
});
});
// delete
app.del('/:id', function () {
2013-04-09 18:33:29 +00:00
var id = req.param('id');
ctx.emit('delete', id, function (done) {
Model.destroy(id, done);
2013-04-09 18:33:29 +00:00
});
});
}