Level 2 (related model) scope over REST - strongloop api

十年热恋 提交于 2019-12-01 00:41:41

Loopback api is based on swagger and scopes is a new concept in loopback.

Currently it doesn't have support for related methods i.e. you cannot access it from a related model i.e category (in your case) but only from model where the scope is defined i.e. game.

Thus you can achieve what you want right now using remote methods.

By Using Remote Methods. Loopback Remote Methods

common/models/category.js add the following lines.

module.exports = function(Category) {

    Category.mature = function(id, filter, callback) {
        var app = this.app;
        var Game = app.models.Game;
        if(filter === undefined){
             filter = {};
        }

        filter.where  = filter.where || {};

        filter.where.categoryId =  id;
        filter.where.mature = true;

        Game.find(filter, function(err, gameArr) {
            if (err) return callback(err);
            console.log(gameArr);
            callback(null, gameArr);
        });
    }

    Category.remoteMethod(
        'mature', {
            accepts: [{
                arg: 'id',
                type: 'number',
                required: true
            },
            {
                arg: 'filter',
                type: 'object',
                required: false
            }
            ],
            // mixing ':id' into the rest url allows $owner to be determined and used for access control
            http: {
                path: '/:id/games/mature',
                verb: 'get'
            },
            returns: {
                arg: 'games',
                type: 'array'
            }
        }
    );

};

Now in your common/models/category.json Add this to your ACL property.

.....
.....
"acls": [
  {
     "principalType": "ROLE",
     "principalId": "$everyone",
     "permission": "ALLOW",
     "property": "mature"
  }
] 

Now you can get all your game of mature type by get method http://0.0.0.0:3000/api/categories/:id/games/mature

Or you can also try the API from loopback-explorer now.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!