Search code examples
stronglooploopback

LoopBack: How to Create an Extended User Model Relation


I'm unable to create a relation from a model extended from the User model. For complete details - see the issue I opened. I created a hasMany / belongsTo relationship from a User extended model named user with a model named account.

common/models/user.json

{
  "name": "user",
  "plural": "users",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "accounts": {
      "type": "hasMany",
      "model": "account",
      "foreignKey": "userId"
    }
  },
  "acls": [{
    "accessType": "EXECUTE",
    "principalType": "ROLE",
    "principalId": "$authenticated",
    "permission": "ALLOW",
    "property": "__create__accounts"
  }],
  "methods": {}
}

common/models/account.json

{
  "name": "account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": "userId"
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "EXECUTE",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": "create"
    }
  ],
  "methods": {}
}

The Issue

In the Loopback API Explorer after creating a user, logging in, and setting the access token I attempt to create an user account entry via POST request (/users/{id}/accounts where {id} represents the user id). The response is a 404 with the following error message:

Shared class  \"User\" has no method handling POST /594fcbeee223ce23620a3e12/accounts?access_token=Dg8qkXIHEck9fS0taCPWxklSVwD6HivN7iVU0lq0SBhaXQ8dMJmo6j8WxQGBNKRD

I've followed documentation and tried a couple things, and even without ACL set at all - I'm seeing this issue. I created a full example project here.

Has anyone run into this before? I'm guessing I need to add more ACL settings to my user model, but it's unclear to me what that would be.


Solution

  • You need to hide the base User model in model-config.json

    {
      "User": {
        "dataSource": "db",
        "public": false
      },
      ...
    }
    

    Since it's visible for remoting, it's still being used over your extended model. There is a small hint in a form of a warning, which could point you to this issue. You see it when the application is being bootstrapped.

    Warning: overriding remoting type user