Expose Model.exists over HTTP HEAD

This commit is contained in:
Raymond Feng 2014-07-30 21:57:45 -07:00
parent 1fd562ecbd
commit ad43d03ebb
2 changed files with 59 additions and 3 deletions

View File

@ -448,7 +448,25 @@ PersistedModel.setupRemoting = function() {
description: 'Check whether a model instance exists in the data source', description: 'Check whether a model instance exists in the data source',
accepts: {arg: 'id', type: 'any', description: 'Model id', required: true}, accepts: {arg: 'id', type: 'any', description: 'Model id', required: true},
returns: {arg: 'exists', type: 'boolean'}, returns: {arg: 'exists', type: 'boolean'},
http: {verb: 'get', path: '/:id/exists'} http: [
{verb: 'get', path: '/:id/exists'},
{verb: 'head', path: '/:id'}
],
rest: {
// After hook to map exists to 200/404 for HEAD
after: function(ctx, cb) {
if(!ctx.result.exists) {
var modelName = ctx.method.sharedClass.name;
var id = ctx.getArgByName('id');
var msg = 'Unknown "' + modelName + '" id "' + id + '".';
var error = new Error(msg);
error.statusCode = error.status = 404;
cb(error);
} else {
cb();
}
}
}
}); });
setRemoting(PersistedModel, 'findById', { setRemoting(PersistedModel, 'findById', {

View File

@ -1,16 +1,54 @@
describe('loopback.rest', function() { describe('loopback.rest', function() {
var MyModel;
beforeEach(function() { beforeEach(function() {
app.dataSource('db', { connector: loopback.Memory }); var ds = app.dataSource('db', { connector: loopback.Memory });
MyModel = ds.createModel('MyModel', {name: String});
}); });
it('works out-of-the-box', function(done) { it('works out-of-the-box', function(done) {
app.model('MyModel', { dataSource: 'db' }); app.model(MyModel);
app.use(loopback.rest()); app.use(loopback.rest());
request(app).get('/mymodels') request(app).get('/mymodels')
.expect(200) .expect(200)
.end(done); .end(done);
}); });
it('should report 404 for GET /:id not found', function(done) {
app.model(MyModel);
app.use(loopback.rest());
request(app).get('/mymodels/1')
.expect(404)
.end(done);
});
it('should report 404 for HEAD /:id not found', function(done) {
app.model(MyModel);
app.use(loopback.rest());
request(app).head('/mymodels/1')
.expect(404)
.end(done);
});
it('should report 200 for GET /:id found', function(done) {
app.model(MyModel);
app.use(loopback.rest());
MyModel.create({name: 'm1'}, function(err, inst) {
request(app).get('/mymodels/' + inst.id)
.expect(200)
.end(done);
});
});
it('should report 200 for HEAD /:id found', function(done) {
app.model(MyModel);
app.use(loopback.rest());
MyModel.create({name: 'm2'}, function(err, inst) {
request(app).head('/mymodels/' + inst.id)
.expect(200)
.end(done);
});
});
it('includes loopback.token when necessary', function(done) { it('includes loopback.token when necessary', function(done) {
givenUserModelWithAuth(); givenUserModelWithAuth();
app.enableAuth(); app.enableAuth();