Can't extend user prototype
Hi there, I encounter a problem on my custom user model (which extends User). This is the only model on which I can't access my custom prototypal methods. When I console.log(app.models.user.prototype) I can't see any of my methods but those of the builtin model ... However they are working on the explorer but not internally.
Any help please ? I just want to do some
app.models.user.findById(userId)
.then(user => user.myCustomPrototypeMethod(parma1, param2)
Is this issue already known ? Maybe I've done something wrong ?
Info : Loopback ^2.36 Loopback-connector-mongodb: 1.17
@pierreclr Where have you created your prototype method ?
In common/user.js but In this file I also require another file in wich I have part of the logique :
common/models
user/contacts.js
user.json
user.js
user.js is like
const app = require('../../server/server');
modules.exports = function(User) {
require('./user/contacts.js')(app, User); // Here I have other prototype methods
User.prototype.custom = function() {} ...
}
@pierreclr It should be possible to add custom prototype methods to any models, including a model extending the built-in User model. Could you please create a small app reproducing the issue per our bug reporting instructions?
@bajtos Could not reproduce in sandbox. Not easy to simulate what happen in a huge app :/ However, I set up a sandbox which (for now) show you a problem : common/user.js.
Note that customer relation is defined in user.json
User.prototype.getCustomerName = function() {
//console.log(this.customer()); // Undefined : Why ??
//console.log(this.customer().name); // Cannot read property name of undeifined
//return this.customer().name;
return 'plop';
}
Thank you @pierreclr for the sandbox app. I am afraid I am not able to reproduce your problem. When I run your app, I see the following output:
[...]
Web server listening at: http://0.0.0.0:3000
Browse your REST API at http://0.0.0.0:3000/explorer
[Function]
When I fix the boot script to actually call the method (user => console.log(user.undefinedPrototypeMethod()), then I receive:
[...]
Web server listening at: http://0.0.0.0:3000
Browse your REST API at http://0.0.0.0:3000/explorer
{ firstName: 'john',
password: '$2a$10$1rjq7j3uvOvD7WJ42skXuOaBax2cZ1wFCoFfhY1gdgGQ0UUkd0hIm',
email: '[email protected]',
customerId: 58b95d2339be11c6e15f7795,
settings: { setting1: 'setting1' },
id: 58b95d2339be11c6e15f7796 }
lol
@bajtos Sorry for this issue. It was due to the way I launched unit test.
@pierreclr user.customer() is async function, you should pass a callback to received the related model. It returns a cached value, which is not set on the first call, that's why you are receiving undefined.
// in your boot script
user.customer(function(err, res) { console.log(res); })
// result printed to the console
{ name: 'customer1', id: 58b97df7dba76de04a14130e }
If feel terribly sorry : I though loopback returns the result in a synchrone way in case of no callback.