105 lines
1.9 KiB
JavaScript
105 lines
1.9 KiB
JavaScript
|
/**
|
||
|
* Expose `Collection`.
|
||
|
*/
|
||
|
|
||
|
module.exports = Collection;
|
||
|
|
||
|
/**
|
||
|
* Module dependencies.
|
||
|
*/
|
||
|
|
||
|
var Resource = require('resource').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;
|
||
|
|
||
|
// collection middleware
|
||
|
this.app.use(function (req, res, next) {
|
||
|
req.asyncEmit('request', next);
|
||
|
});
|
||
|
|
||
|
// setup http routes
|
||
|
// this.setupRoutes(this.app);
|
||
|
|
||
|
debug('created with options', options);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Inherit from `Resource`.
|
||
|
*/
|
||
|
|
||
|
inherits(Collection, Resource);
|
||
|
|
||
|
/**
|
||
|
* Dependencies.
|
||
|
*/
|
||
|
|
||
|
Collection.dependencies = {
|
||
|
'store': 'store'
|
||
|
}
|
||
|
|
||
|
Collection.prototype.setupRoutes = function (app) {
|
||
|
var store = this.store;
|
||
|
var done = this.done;
|
||
|
var Model = this.store;
|
||
|
var emit = this.asyncEmit;
|
||
|
|
||
|
// create
|
||
|
app.post('/', create);
|
||
|
app.post('/new', create);
|
||
|
|
||
|
function create(req, res, next) {
|
||
|
req.asyncEmit('create', function () {
|
||
|
var o = store.save(req.body, res.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;
|
||
|
}
|
||
|
|
||
|
req.asyncEmit('query', query, function () {
|
||
|
store.all(query, res.done);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// update
|
||
|
app.put('/:id', function (req, res) {
|
||
|
req.asyncEmit('update', req.body, function () {
|
||
|
store.updateAttributes(req.body, res.done);
|
||
|
});
|
||
|
});
|
||
|
|
||
|
// delete
|
||
|
app.destroy('/:id', function () {
|
||
|
var id = req.param('id');
|
||
|
|
||
|
req.asyncEmit('delete', id, function () {
|
||
|
store.destroy(id, res.done);
|
||
|
});
|
||
|
});
|
||
|
}
|