Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Non-Static (instance) remote methods for loopback
var loopback = require('loopback');
// HINT(s):
// Getting the app object: http://docs.strongloop.com/display/public/LB/Working+with+LoopBack+objects
// From a model script: http://docs.strongloop.com/display/public/LB/Working+with+LoopBack+objects#WorkingwithLoopBackobjects-Fromamodelscript
module.exports = function(StoreModel) {
StoreModel.prototype.instanceRemoteMethodSignature = function(cb) {
console.log('print this instance object: ', this);
cb(null);
};
StoreModel.remoteMethod(
'__get__instance-remote-method-signature',
{
isStatic: false,
accepts: [],
http: {path:'/instance-remote-method-signature', verb: 'get'}
}
);
StoreModel.staticMethodSignature = function(id, cb) {
console.log('print this instance object: ', this);
StoreModel.findById(id,function(err, instances){
if(err){
cb(err);
}
console.log('print object: ', instances);
cb(null);
});
};
StoreModel.remoteMethod(
'__get__static-method-signature',
{
isStatic: false,
accepts: [
{arg: 'id', type: 'number', required: true}
],
http: {path:'/:id/static-method-signature', verb: 'get'}
}
);
};
@ebarault

This comment has been minimized.

Copy link

ebarault commented Apr 21, 2016

you saved my day

@florianeyzat

This comment has been minimized.

Copy link

florianeyzat commented Jun 15, 2016

Thanks!

@nammaianh

This comment has been minimized.

Copy link

nammaianh commented Aug 31, 2016

screen shot 2016-09-01 at 3 01 44 am

I think you should set isStatic field to be true because the method was not defined for the prototype

@nidhhoggr

This comment has been minimized.

Copy link

nidhhoggr commented Dec 23, 2016

I believe @nammaianh is correct the isStatic property for the __get__static-method-signature remote method should be set to true. when you read the code of loopback model.js the whole purpose of the isStatic property is to grab the instance of the model by the foreign key with the models builtin getter function. It also injects the arguments of id in the remote method accepts property. The prototype method receives the instance via the built in getter function when the remote method is set to false. Its also important to note that for every defined remote method, if isStatic is undefined then isStatic is set to true. In conclusion not only should isStatic be set to true but leaving it omitting the property is also a valid option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.