Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loopback hasMany relation remoteMethod hook

Tags:

loopbackjs

I am using loopback for develop my own website. But recently I had a problem of hasMany remoteMethod. Here is the problem: I have two models :

person.json:

{
  "name": "Person",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    /*...
    ....
    */
  },
  "validations": [],
  "relations": {
    "friends": {
      "type": "hasMany",
      "model": "Friend",
      "foreignKey": "personId"
    }
  },
  "acls": [],
  "methods": []
}

friend.json

friend.json:
{
  "name": "friend",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    /*...
    ....
    */
  },
  "validations": [],
  "relations": {

  },
  "acls": [],
  "methods": []
}

I want to use beforeRemote when I call POST /api/Persons/{id}/friends.

So I code in person.js

    module.exports = function(Person) {
        Person.beforeRemote('__create__friends', function(ctx, instance, next) {
            /*
                code here
            */
        });
    };

But it does not work!

At the beginning I think it's the matter of '__create__friends',but when I code in person.js like :

    module.exports = function(Person) {
        Person.disableRemoteMethod('__create__friends');
    };

I could disable the '__create__friends' successfully.

So what's the problem?

Can anyone help me?

like image 997
王如锵 Avatar asked Apr 28 '26 08:04

王如锵


1 Answers

Because methods for related models are attached to Person prototype, you should register hook like this:

Person.beforeRemote('prototype.__create__friends', function() {
    next()
})
like image 78
IvanZh Avatar answered May 02 '26 09:05

IvanZh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!