Reputation: 1961
I have Notification model which looks like this
"use strict";
module.exports = function(Notification) {
};
And I have another model which is Post:
"use strict";
module.exports = function(Post) {
Post.prototype.postLike = function(options, cb) {
this.likes.add(options.accessToken.userId);
cb(null, "sucess");
};
Post.remoteMethod("postLike", {
isStatic: false,
accepts: [{ arg: "options", type: "object", http: "optionsFromRequest" }],
returns: { arg: "name", type: "string" },
http: { path: "/like", verb: "post" }
});
}
What I want is to add afterRemote method of Post inside of notification model ?
Is it possible in loopback ?
It should looks like :
"use strict";
module.exports = function(Notification) {
var app = require("../../server/server.js");
var post = app.models.Post;
post.afterRemote('prototype.postLike', function(context, like, next) {
console.log('Notification after save for Like comment');
});
};
But this does not work.
NOTE: I can do it Post model itself, but I want to add all of my notification logic in Notification model for simplification and future customization.
Upvotes: 0
Views: 476
Reputation: 9396
You can use events to do.
Loopback application emits started
event when it started after all boot scripts loaded here
and in Notification
model do like this :
"use strict";
module.exports = function(Notification) {
var app = require("../../server/server.js");
app.on('started', function(){
var post = app.models.Post;
post.afterRemote('prototype.postLike', function(context, like, next) {
console.log('Notification after save for Like comment');
});
});
};
Or create a boot script and emit a custom event like 'allModelsLoaded'. So make sure the boot script is the last one to be run. Boot scripts run in alphabetic order by default. So make z.js
and emit that custom event there then listen to that event in Notification
model.
Upvotes: 2
Reputation: 317
Loopback boot process first loads models, and then invoke boot scripts once all models have been loaded. If your aim is to consolidate things across models, then it is better to do this in a boot script, rather than in model.js file.
Upvotes: 1