loopback/node_modules/collection/lib/collection.js

132 lines
2.5 KiB
JavaScript

/**
* Expose `Collection`.
*/
module.exports = Collection;
/**
* Module dependencies.
*/
var Resource = require('resource')
, debug = require('debug')('collection')
, util = require('util')
, inherits = util.inherits
, assert = require('assert');
/**
* Create a new `Collection` with the given `options`.
*
* @param {Object} options
* @return {Collection}
*/
function Collection(options) {
Resource.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 `Resource`.
*/
inherits(Collection, Resource);
/**
* Dependencies.
*/
Collection.dependencies = {
'model': 'model'
}
Collection.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);
});
});
}