Contextify DAO and relation methods

Modify remoting metadata of data-access methods in PersistedModel
and relation method in Model and add an "options" argument to "accepts"
list.
This commit is contained in:
Miroslav Bajtoš 2016-09-20 10:54:41 +02:00
parent 4de3aa77e3
commit 60ea3e96bc
6 changed files with 607 additions and 67 deletions

View File

@ -9,6 +9,7 @@
'use strict';
var g = require('./globalize');
var assert = require('assert');
var debug = require('debug')('loopback:model');
var RemoteObjects = require('strong-remoting');
var SharedClass = require('strong-remoting').SharedClass;
var extend = require('util')._extend;
@ -136,15 +137,29 @@ module.exports = function(registry) {
);
// support remoting prototype methods
ModelCtor.sharedCtor = function(data, id, fn) {
ModelCtor.sharedCtor = function(data, id, options, fn) {
var ModelCtor = this;
if (typeof data === 'function') {
var isRemoteInvocationWithOptions = typeof data !== 'object' &&
typeof id === 'object' &&
typeof options === 'function';
if (isRemoteInvocationWithOptions) {
// sharedCtor(id, options, fn)
fn = options;
options = id;
id = data;
data = null;
} else if (typeof data === 'function') {
// sharedCtor(fn)
fn = data;
data = null;
id = null;
options = null;
} else if (typeof id === 'function') {
// sharedCtor(data, fn)
// sharedCtor(id, fn)
fn = id;
options = null;
if (typeof data !== 'object') {
id = data;
@ -161,7 +176,8 @@ module.exports = function(registry) {
} else if (data) {
fn(null, new ModelCtor(data));
} else if (id) {
ModelCtor.findById(id, function(err, model) {
var filter = {};
ModelCtor.findById(id, filter, options, function(err, model) {
if (err) {
fn(err);
} else if (model) {
@ -183,6 +199,7 @@ module.exports = function(registry) {
{arg: 'id', type: 'any', required: true, http: {source: 'path'},
description: idDesc},
// {arg: 'instance', type: 'object', http: {source: 'body'}}
{arg: 'options', type: 'object', http: createOptionsViaModelMethod},
];
ModelCtor.sharedCtor.http = [
@ -232,6 +249,14 @@ module.exports = function(registry) {
// resolve relation functions
sharedClass.resolve(function resolver(define) {
var relations = ModelCtor.relations || {};
var defineRaw = define;
define = function(name, options, fn) {
if (options.accepts) {
options = extend({}, options);
options.accepts = setupOptionsArgs(options.accepts);
}
defineRaw(name, options, fn);
};
// get the relations
for (var relationName in relations) {
@ -439,7 +464,7 @@ module.exports = function(registry) {
return accepts.map(function(arg) {
if (arg.http && arg.http === 'optionsFromRequest') {
// deep clone to preserve the input value
// clone to preserve the input value
arg = extend({}, arg);
arg.http = createOptionsViaModelMethod;
}
@ -454,6 +479,7 @@ module.exports = function(registry) {
return EMPTY_OPTIONS;
if (typeof ModelCtor.createOptionsFromRemotingContext !== 'function')
return EMPTY_OPTIONS;
debug('createOptionsFromRemotingContext for %s', ctx.method.stringName);
return ModelCtor.createOptionsFromRemotingContext(ctx);
}
@ -494,7 +520,10 @@ module.exports = function(registry) {
define('__get__' + relationName, {
isStatic: false,
http: {verb: 'get', path: '/' + pathName},
accepts: {arg: 'refresh', type: 'boolean', http: {source: 'query'}},
accepts: [
{arg: 'refresh', type: 'boolean', http: {source: 'query'}},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
accessType: 'READ',
description: format('Fetches belongsTo relation %s.', relationName),
returns: {arg: relationName, type: modelName, root: true},
@ -519,7 +548,10 @@ module.exports = function(registry) {
define('__get__' + relationName, {
isStatic: false,
http: {verb: 'get', path: '/' + pathName},
accepts: {arg: 'refresh', type: 'boolean', http: {source: 'query'}},
accepts: [
{arg: 'refresh', type: 'boolean', http: {source: 'query'}},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Fetches hasOne relation %s.', relationName),
accessType: 'READ',
returns: {arg: relationName, type: relation.modelTo.modelName, root: true},
@ -529,7 +561,13 @@ module.exports = function(registry) {
define('__create__' + relationName, {
isStatic: false,
http: {verb: 'post', path: '/' + pathName},
accepts: {arg: 'data', type: 'object', model: toModelName, http: {source: 'body'}},
accepts: [
{
arg: 'data', type: 'object', model: toModelName,
http: {source: 'body'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Creates a new instance in %s of this model.', relationName),
accessType: 'WRITE',
returns: {arg: 'data', type: toModelName, root: true},
@ -538,7 +576,13 @@ module.exports = function(registry) {
define('__update__' + relationName, {
isStatic: false,
http: {verb: 'put', path: '/' + pathName},
accepts: {arg: 'data', type: 'object', model: toModelName, http: {source: 'body'}},
accepts: [
{
arg: 'data', type: 'object', model: toModelName,
http: {source: 'body'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Update %s of this model.', relationName),
accessType: 'WRITE',
returns: {arg: 'data', type: toModelName, root: true},
@ -547,6 +591,9 @@ module.exports = function(registry) {
define('__destroy__' + relationName, {
isStatic: false,
http: {verb: 'delete', path: '/' + pathName},
accepts: [
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Deletes %s of this model.', relationName),
accessType: 'WRITE',
});
@ -560,10 +607,15 @@ module.exports = function(registry) {
define('__findById__' + relationName, {
isStatic: false,
http: {verb: 'get', path: '/' + pathName + '/:fk'},
accepts: {arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'}},
accepts: [
{
arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Find a related item by id for %s.', relationName),
accessType: 'READ',
returns: {arg: 'result', type: toModelName, root: true},
@ -574,10 +626,15 @@ module.exports = function(registry) {
define('__destroyById__' + relationName, {
isStatic: false,
http: {verb: 'delete', path: '/' + pathName + '/:fk'},
accepts: {arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'}},
accepts: [
{
arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Delete a related item by id for %s.', relationName),
accessType: 'WRITE',
returns: [],
@ -593,6 +650,7 @@ module.exports = function(registry) {
required: true,
http: {source: 'path'}},
{arg: 'data', type: 'object', model: toModelName, http: {source: 'body'}},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Update a related item by id for %s.', relationName),
accessType: 'WRITE',
@ -618,7 +676,10 @@ module.exports = function(registry) {
accepts: [{arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'}}].concat(accepts),
http: {source: 'path'}},
].concat(accepts).concat([
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
]),
description: format('Add a related item by id for %s.', relationName),
accessType: 'WRITE',
returns: {arg: relationName, type: modelThrough.modelName, root: true},
@ -628,10 +689,15 @@ module.exports = function(registry) {
define('__unlink__' + relationName, {
isStatic: false,
http: {verb: 'delete', path: '/' + pathName + '/rel/:fk'},
accepts: {arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'}},
accepts: [
{
arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Remove the %s relation to an item by id.', relationName),
accessType: 'WRITE',
returns: [],
@ -643,10 +709,15 @@ module.exports = function(registry) {
define('__exists__' + relationName, {
isStatic: false,
http: {verb: 'head', path: '/' + pathName + '/rel/:fk'},
accepts: {arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'}},
accepts: [
{
arg: 'fk', type: 'any',
description: format('Foreign key for %s', relationName),
required: true,
http: {source: 'path'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Check the existence of %s relation to an item by id.', relationName),
accessType: 'READ',
returns: {arg: 'exists', type: 'boolean', root: true},
@ -689,7 +760,10 @@ module.exports = function(registry) {
define('__get__' + scopeName, {
isStatic: isStatic,
http: {verb: 'get', path: '/' + pathName},
accepts: {arg: 'filter', type: 'object'},
accepts: [
{arg: 'filter', type: 'object'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Queries %s of %s.', scopeName, this.modelName),
accessType: 'READ',
returns: {arg: scopeName, type: [toModelName], root: true},
@ -698,13 +772,16 @@ module.exports = function(registry) {
define('__create__' + scopeName, {
isStatic: isStatic,
http: {verb: 'post', path: '/' + pathName},
accepts: {
arg: 'data',
type: 'object',
allowArray: true,
model: toModelName,
http: {source: 'body'},
},
accepts: [
{
arg: 'data',
type: 'object',
allowArray: true,
model: toModelName,
http: {source: 'body'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Creates a new instance in %s of this model.', scopeName),
accessType: 'WRITE',
returns: {arg: 'data', type: toModelName, root: true},
@ -713,6 +790,16 @@ module.exports = function(registry) {
define('__delete__' + scopeName, {
isStatic: isStatic,
http: {verb: 'delete', path: '/' + pathName},
accepts: [
{
arg: 'where', type: 'object',
// The "where" argument is not exposed in the REST API
// but we need to provide a value so that we can pass "options"
// as the third argument.
http: function(ctx) { return undefined; },
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Deletes all %s of this model.', scopeName),
accessType: 'WRITE',
});
@ -720,8 +807,13 @@ module.exports = function(registry) {
define('__count__' + scopeName, {
isStatic: isStatic,
http: {verb: 'get', path: '/' + pathName + '/count'},
accepts: {arg: 'where', type: 'object',
description: 'Criteria to match model instances'},
accepts: [
{
arg: 'where', type: 'object',
description: 'Criteria to match model instances',
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
description: format('Counts %s of %s.', scopeName, this.modelName),
accessType: 'READ',
returns: {arg: 'count', type: 'number'},

View File

@ -639,11 +639,14 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'create', {
description: 'Create a new instance of the model and persist it into the data source.',
accessType: 'WRITE',
accepts: {
arg: 'data', type: 'object', model: typeName, allowArray: true,
description: 'Model instance data',
http: {source: 'body'},
},
accepts: [
{
arg: 'data', type: 'object', model: typeName, allowArray: true,
description: 'Model instance data',
http: {source: 'body'},
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: {verb: 'post', path: '/'},
});
@ -653,10 +656,13 @@ module.exports = function(registry) {
description: 'Patch an existing model instance or insert a new one ' +
'into the data source.',
accessType: 'WRITE',
accepts: {
arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
description: 'Model instance data',
},
accepts: [
{
arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
description: 'Model instance data',
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: [{verb: 'patch', path: '/'}],
};
@ -669,11 +675,14 @@ module.exports = function(registry) {
var replaceOrCreateOptions = {
description: 'Replace an existing model instance or insert a new one into the data source.',
accessType: 'WRITE',
accepts: {
arg: 'data', type: 'object', model: typeName,
http: {source: 'body'},
description: 'Model instance data',
},
accepts: [
{
arg: 'data', type: 'object', model: typeName,
http: {source: 'body'},
description: 'Model instance data',
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: [{verb: 'post', path: '/replaceOrCreate'}],
};
@ -694,6 +703,7 @@ module.exports = function(registry) {
description: 'Criteria to match model instances'},
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
description: 'An object of model property name/value pairs'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: {verb: 'post', path: '/upsertWithWhere'},
@ -702,7 +712,10 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'exists', {
description: 'Check whether a model instance exists in the data source.',
accessType: 'READ',
accepts: {arg: 'id', type: 'any', description: 'Model id', required: true},
accepts: [
{arg: 'id', type: 'any', description: 'Model id', required: true},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'exists', type: 'boolean'},
http: [
{verb: 'get', path: '/:id/exists'},
@ -738,6 +751,7 @@ module.exports = function(registry) {
http: {source: 'path'}},
{arg: 'filter', type: 'object',
description: 'Filter defining fields and include'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: {verb: 'get', path: '/:id'},
@ -751,7 +765,8 @@ module.exports = function(registry) {
{arg: 'id', type: 'any', description: 'Model id', required: true,
http: {source: 'path'}},
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'}, description:
'Model instance data'},
'Model instance data'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: [{verb: 'post', path: '/:id/replace'}],
@ -766,8 +781,11 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'find', {
description: 'Find all instances of the model matched by filter from the data source.',
accessType: 'READ',
accepts: {arg: 'filter', type: 'object', description:
'Filter defining fields, where, include, order, offset, and limit'},
accepts: [
{arg: 'filter', type: 'object', description:
'Filter defining fields, where, include, order, offset, and limit'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: [typeName], root: true},
http: {verb: 'get', path: '/'},
});
@ -775,8 +793,11 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'findOne', {
description: 'Find first instance of the model matched by filter from the data source.',
accessType: 'READ',
accepts: {arg: 'filter', type: 'object', description:
'Filter defining fields, where, include, order, offset, and limit'},
accepts: [
{arg: 'filter', type: 'object', description:
'Filter defining fields, where, include, order, offset, and limit'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: {verb: 'get', path: '/findOne'},
rest: {after: convertNullToNotFoundError},
@ -785,7 +806,10 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'destroyAll', {
description: 'Delete all matching records.',
accessType: 'WRITE',
accepts: {arg: 'where', type: 'object', description: 'filter.where object'},
accepts: [
{arg: 'where', type: 'object', description: 'filter.where object'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {
arg: 'count',
type: 'object',
@ -805,6 +829,7 @@ module.exports = function(registry) {
description: 'Criteria to match model instances'},
{arg: 'data', type: 'object', model: typeName, http: {source: 'body'},
description: 'An object of model property name/value pairs'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {
arg: 'info',
@ -824,8 +849,11 @@ module.exports = function(registry) {
aliases: ['destroyById', 'removeById'],
description: 'Delete a model instance by {{id}} from the data source.',
accessType: 'WRITE',
accepts: {arg: 'id', type: 'any', description: 'Model id', required: true,
http: {source: 'path'}},
accepts: [
{arg: 'id', type: 'any', description: 'Model id', required: true,
http: {source: 'path'}},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
http: {verb: 'del', path: '/:id'},
returns: {arg: 'count', type: 'object', root: true},
});
@ -833,7 +861,10 @@ module.exports = function(registry) {
setRemoting(PersistedModel, 'count', {
description: 'Count instances of the model matched by where from the data source.',
accessType: 'READ',
accepts: {arg: 'where', type: 'object', description: 'Criteria to match model instances'},
accepts: [
{arg: 'where', type: 'object', description: 'Criteria to match model instances'},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'count', type: 'number'},
http: {verb: 'get', path: '/count'},
});
@ -843,11 +874,14 @@ module.exports = function(registry) {
description: 'Patch attributes for a model instance and persist it into ' +
'the data source.',
accessType: 'WRITE',
accepts: {
arg: 'data', type: 'object', model: typeName,
http: {source: 'body'},
description: 'An object of model property name/value pairs',
},
accepts: [
{
arg: 'data', type: 'object', model: typeName,
http: {source: 'body'},
description: 'An object of model property name/value pairs',
},
{arg: 'options', type: 'object', http: 'optionsFromRequest'},
],
returns: {arg: 'data', type: typeName, root: true},
http: [{verb: 'patch', path: '/'}],
};

View File

@ -92,7 +92,8 @@
"sinon-chai": "^2.8.0",
"strong-error-handler": "^1.0.1",
"strong-task-emitter": "^0.0.6",
"supertest": "^2.0.0"
"supertest": "^2.0.0",
"supertest-as-promised": "^4.0.2"
},
"repository": {
"type": "git",

View File

@ -0,0 +1,411 @@
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: loopback
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var expect = require('chai').expect;
var loopback = require('..');
var supertest = require('supertest-as-promised')(require('bluebird'));
describe('OptionsFromRemotingContext', function() {
var app, request, accessToken, userId, Product, actualOptions;
beforeEach(setupAppAndRequest);
beforeEach(resetActualOptions);
context('when making updates via REST', function() {
beforeEach(observeOptionsBeforeSave);
it('injects options to create()', function() {
return request.post('/products')
.send({name: 'Pen'})
.expect(200)
.then(expectInjectedOptions);
});
it('injects options to patchOrCreate()', function() {
return request.patch('/products')
.send({id: 1, name: 'Pen'})
.expect(200)
.then(expectInjectedOptions);
});
it('injects options to replaceOrCreate()', function() {
return request.put('/products')
.send({id: 1, name: 'Pen'})
.expect(200)
.then(expectInjectedOptions);
});
it('injects options to patchOrCreateWithWhere()', function() {
return request.post('/products/upsertWithWhere?where[name]=Pen')
.send({name: 'Pencil'})
.expect(200)
.then(expectInjectedOptions);
});
it('injects options to replaceById()', function() {
return Product.create({id: 1, name: 'Pen'})
.then(function(p) {
return request.put('/products/1')
.send({name: 'Pencil'})
.expect(200);
})
.then(expectInjectedOptions);
});
it('injects options to prototype.patchAttributes()', function() {
return Product.create({id: 1, name: 'Pen'})
.then(function(p) {
return request.patch('/products/1')
.send({name: 'Pencil'})
.expect(200);
})
.then(expectInjectedOptions);
});
it('injects options to updateAll()', function() {
return request.post('/products/update?where[name]=Pen')
.send({name: 'Pencil'})
.expect(200)
.then(expectInjectedOptions);
});
});
context('when deleting via REST', function() {
beforeEach(observeOptionsBeforeDelete);
it('injects options to deleteById()', function() {
return Product.create({id: 1, name: 'Pen'})
.then(function(p) {
return request.delete('/products/1').expect(200);
})
.then(expectInjectedOptions);
});
});
context('when querying via REST', function() {
beforeEach(observeOptionsOnAccess);
beforeEach(givenProductId1);
it('injects options to find()', function() {
return request.get('/products').expect(200)
.then(expectInjectedOptions);
});
it('injects options to findById()', function() {
return request.get('/products/1').expect(200)
.then(expectInjectedOptions);
});
it('injects options to findOne()', function() {
return request.get('/products/findOne?where[id]=1').expect(200)
.then(expectInjectedOptions);
});
it('injects options to exists()', function() {
return request.head('/products/1').expect(200)
.then(expectInjectedOptions);
});
it('injects options to count()', function() {
return request.get('/products/count').expect(200)
.then(expectInjectedOptions);
});
});
context('when invoking prototype methods', function() {
beforeEach(observeOptionsOnAccess);
beforeEach(givenProductId1);
it('injects options to sharedCtor', function() {
Product.prototype.dummy = function(cb) { cb(); };
Product.remoteMethod('prototype.dummy', {});
return request.post('/products/1/dummy').expect(204)
.then(expectInjectedOptions);
});
});
// Catch: because relations methods are defined on "modelFrom",
// they will invoke createOptionsFromRemotingContext on "modelFrom" too,
// despite the fact that under the hood a method on "modelTo" is called.
context('hasManyThrough', function() {
var Category, ThroughModel;
beforeEach(givenCategoryHasManyProductsThroughAnotherModel);
beforeEach(givenCategoryAndProduct);
it('injects options to findById', function() {
observeOptionsOnAccess(Product);
return request.get('/categories/1/products/1').expect(200)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to destroyById', function() {
observeOptionsBeforeDelete(Product);
return request.del('/categories/1/products/1').expect(204)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to updateById', function() {
observeOptionsBeforeSave(Product);
return request.put('/categories/1/products/1')
.send({description: 'a description'})
.expect(200)
.then(expectInjectedOptions);
});
context('through-model operations', function() {
it('injects options to link', function() {
observeOptionsBeforeSave(ThroughModel);
return Product.create({id: 2, name: 'Car2'})
.then(function() {
return request.put('/categories/1/products/rel/2')
.send({description: 'a description'})
.expect(200);
})
.then(expectOptionsInjectedFromCategory);
});
it('injects options to unlink', function() {
observeOptionsBeforeDelete(ThroughModel);
return request.del('/categories/1/products/rel/1').expect(204)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to exists', function() {
observeOptionsOnAccess(ThroughModel);
return request.head('/categories/1/products/rel/1').expect(200)
.then(expectOptionsInjectedFromCategory);
});
});
context('scope operations', function() {
it('injects options to get', function() {
observeOptionsOnAccess(Product);
return request.get('/categories/1/products').expect(200)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to create', function() {
observeOptionsBeforeSave(Product);
return request.post('/categories/1/products')
.send({name: 'Pen'})
.expect(200)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to delete', function() {
observeOptionsBeforeDelete(ThroughModel);
return request.del('/categories/1/products').expect(204)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to count', function() {
observeOptionsOnAccess(ThroughModel);
return request.get('/categories/1/products/count').expect(200)
.then(expectOptionsInjectedFromCategory);
});
});
function givenCategoryHasManyProductsThroughAnotherModel() {
Category = app.registry.createModel(
'Category',
{name: String},
{forceId: false, replaceOnPUT: true});
app.model(Category, {dataSource: 'db'});
// This is a shortcut for creating CategoryProduct "through" model
Category.hasAndBelongsToMany(Product);
Category.createOptionsFromRemotingContext = function(ctx) {
return {injectedFrom: 'Category'};
};
ThroughModel = app.registry.getModel('CategoryProduct');
}
function givenCategoryAndProduct() {
return Category.create({id: 1, name: 'First Category'})
.then(function(cat) {
return cat.products.create({id: 1, name: 'Pen'});
});
}
function expectOptionsInjectedFromCategory() {
expect(actualOptions).to.have.property('injectedFrom', 'Category');
}
});
context('hasOne', function() {
var Category;
beforeEach(givenCategoryHasOneProduct);
beforeEach(givenCategoryId1);
it('injects options to get', function() {
observeOptionsOnAccess(Product);
return givenProductInCategory1()
.then(function() {
return request.get('/categories/1/product').expect(200);
})
.then(expectOptionsInjectedFromCategory);
});
it('injects options to create', function() {
observeOptionsBeforeSave(Product);
return request.post('/categories/1/product')
.send({name: 'Pen'})
.expect(200)
.then(expectOptionsInjectedFromCategory);
});
it('injects options to update', function() {
return givenProductInCategory1()
.then(function() {
observeOptionsBeforeSave(Product);
return request.put('/categories/1/product')
.send({description: 'a description'})
.expect(200);
})
.then(expectInjectedOptions);
});
it('injects options to destroy', function() {
observeOptionsBeforeDelete(Product);
return givenProductInCategory1()
.then(function() {
return request.del('/categories/1/product').expect(204);
})
.then(expectOptionsInjectedFromCategory);
});
function givenCategoryHasOneProduct() {
Category = app.registry.createModel(
'Category',
{name: String},
{forceId: false, replaceOnPUT: true});
app.model(Category, {dataSource: 'db'});
Category.hasOne(Product);
Category.createOptionsFromRemotingContext = function(ctx) {
return {injectedFrom: 'Category'};
};
}
function givenCategoryId1() {
return Category.create({id: 1, name: 'First Category'});
}
function givenProductInCategory1() {
return Product.create({id: 1, name: 'Pen', categoryId: 1});
}
function expectOptionsInjectedFromCategory() {
expect(actualOptions).to.have.property('injectedFrom', 'Category');
}
});
context('belongsTo', function() {
var Category;
beforeEach(givenCategoryBelongsToProduct);
it('injects options to get', function() {
observeOptionsOnAccess(Product);
return Product.create({id: 1, name: 'Pen'})
.then(function() {
return Category.create({id: 1, name: 'a name', productId: 1});
})
.then(function() {
return request.get('/categories/1/product').expect(200);
})
.then(expectOptionsInjectedFromCategory);
});
function givenCategoryBelongsToProduct() {
Category = app.registry.createModel(
'Category',
{name: String},
{forceId: false, replaceOnPUT: true});
app.model(Category, {dataSource: 'db'});
Category.belongsTo(Product);
Category.createOptionsFromRemotingContext = function(ctx) {
return {injectedFrom: 'Category'};
};
}
function givenCategoryId1() {
return Category.create({id: 1, name: 'First Category'});
}
function givenProductInCategory1() {
return Product.create({id: 1, name: 'Pen', categoryId: 1});
}
function expectOptionsInjectedFromCategory() {
expect(actualOptions).to.have.property('injectedFrom', 'Category');
}
});
function setupAppAndRequest() {
app = loopback({localRegistry: true});
app.dataSource('db', {connector: 'memory'});
Product = app.registry.createModel(
'Product',
{name: String},
{forceId: false, replaceOnPUT: true});
Product.createOptionsFromRemotingContext = function(ctx) {
return {injectedFrom: 'Product'};
};
app.model(Product, {dataSource: 'db'});
app.use(loopback.rest());
request = supertest(app);
}
function resetActualOptions() {
actualOptions = undefined;
}
function observeOptionsBeforeSave() {
var Model = arguments[0] || Product;
Model.observe('before save', function(ctx, next) {
actualOptions = ctx.options;
next();
});
}
function observeOptionsBeforeDelete() {
var Model = arguments[0] || Product;
Model.observe('before delete', function(ctx, next) {
actualOptions = ctx.options;
next();
});
}
function observeOptionsOnAccess() {
var Model = arguments[0] || Product;
Model.observe('access', function(ctx, next) {
actualOptions = ctx.options;
next();
});
}
function givenProductId1() {
return Product.create({id: 1, name: 'Pen'});
}
function expectInjectedOptions(name) {
expect(actualOptions).to.have.property('injectedFrom');
}
});

View File

@ -82,7 +82,7 @@ describe('RemoteConnector', function() {
var ServerModel = this.ServerModel;
ServerModel.create = function(data, cb) {
ServerModel.create = function(data, options, cb) {
calledServerCreate = true;
data.id = 1;
cb(null, data);

View File

@ -280,7 +280,9 @@ function formatMethod(m) {
arr.push([
m.name,
'(',
m.accepts.map(function(a) {
m.accepts.filter(function(a) {
return !(a.http && typeof a.http === 'function');
}).map(function(a) {
return a.arg + ':' + a.type + (a.model ? ':' + a.model : '');
}).join(','),
')',