Ward Beullens
Ward Beullens

Reputation: 403

What loopback hook should I use?

I am trying to do the following thing:

I have a model, say myModel which has some method calculateSomething. I defined that function by writing something like this in the MyModel.js file:

MyModel.prototype.calculateSomething = function(cb){
    ...
    return cb(null,result)
} 

Now I want to include the result of calculateSomething in the json whenever an instance of MyModel is returned from the api.

How do I do this? I tried using the "loaded" hook, but I believe this hook gets executed before the MyModel instance is created, so I can't call the calculateSomehing method there.

EDIT: It turns out that I can just use the "loaded" hook. I can use the ctx.instance in the hook to get the object.

I was confused by the documentation : "LoopBack invokes this hook after the connector fetches data, but before creating a model instance from that data". Is the documentation wrong or am I misunderstanding it?

Upvotes: 1

Views: 379

Answers (1)

Yohanes Gultom
Yohanes Gultom

Reputation: 3842

How about using Remote Hooks (on mymodel.js):

// run before any static method eg. MyModel.find
MyModel.beforeRemote('*', function(ctx, myModel, next) {
  myModel.calculateSomething(function(err, something) {
    if (err) throw err

    myModel.something = something
    next()
  })
});

OR

If you need to do it on object initialization phase (while operation hook loaded seems to be not working) maybe you can try the model hook afterInitialize assuming no async call invoked from calculateSomething:

MyModel.afterInitialize = function() {
    this.something = this.calculateSomething(function(err, result) {
        return result
    })
}

OR

As discussed below, if you need do async call and/or want to have this logic on subclasses, I think you should consider implementing createSomething not as object/prototype method but as a mixins. I haven't tried this personally though but it looks quite suitable to your need.

Upvotes: 1

Related Questions