用相关模型数扩展模型

时间:2019-07-15 16:13:29

标签: node.js loopbackjs

我正在尝试构建一个具有环回的简单博客。我想用评论数量来扩展获取帖子。

我的想法有两种可能。 1)通过评论的数量来扩展get-post的响应,这是我最喜欢的方式,但是我不知道如何扩展存储库。 2)我试图观察保存的评论并获得posts-model,但是我无法更改它。

post.json

{
  "name": "post",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "title": {
      "type": "string",
      "required": true
    },
    "content": {
      "type": "string",
      "required": true
    }
    "published": {
      "type": "boolean",
      "required": true,
      "default": false
    }
    "commentCount": {
      "type": "number",
      "default": 0
    }
  },
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": ""
    },
    "comments": {
      "type": "hasMany",
      "model": "comment",
      "foreignKey": ""
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW"
    },
    {
      "accessType": "EXECUTE",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW",
      "property": "find"
    },
    {
      "accessType": "EXECUTE",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": "create"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW"
    },
    {
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW",
      "property": [
        "__create__comments",
        "__get__comments"
      ]
    },
    {
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW",
      "property": "__delete__comments"
    }
  ],
  "methods": {}
}

comment.json

{
  "name": "comment",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "content": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "user",
      "foreignKey": ""
    },
    "idea": {
      "type": "belongsTo",
      "model": "post",
      "foreignKey": ""
    }
  },
  "acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$everyone",
      "permission": "DENY"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "admin",
      "permission": "ALLOW"
    },
    {
      "accessType": "READ",
      "principalType": "ROLE",
      "principalId": "$authenticated",
      "permission": "ALLOW"
    },
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$owner",
      "permission": "ALLOW"
    }
  ],
  "methods": {}
}

comment.js ##

var loopback = require('loopback');

module.exports = function(Comment) {
    Comment.observe('after save', function(ctx, userInstance, next) {
      var postId = ctx.instance.postId;

// loopback.getModel('post').definition.rawProperties.commentCount... something... something... 

    });
};

我对环回还很陌生,我不知道实现该解决方案的最佳方法是什么。也许您还有第三种更好的方法?也许任何人都可以帮助我完成comment.js。

1 个答案:

答案 0 :(得分:2)

Fisrt,在您的comment.json中,您写的是idea,而不是post

 "post": {  //change here
      "type": "belongsTo",
      "model": "post",
      "foreignKey": ""
    }

第二,您只需在commentCount方法中的与您的评论链接的post中添加一个after save,然后更新post的属性:

'use strict';

var app = require('../../server/server');
var models = app.models;
var Post;
// pattern to get your models on start event
app.on('started', function () {
    Post = models.post;
});

module.exports = function(Comment) {
   Comment.observe('after save', function(ctx, next) {
      // only add a commentCount if it's a new instance
      if (ctx.instance && ctx.isNewInstance && ctx.instance.postId) {
          Post.findOne({where: {id: ctx.instance.postId}}, function (err, post) {
              if (!err) {
                 post.updateAttributes({commentCount: post.commentCount++});
              }
          });
      }
      next();
   });
};

另一种解决方案是在customGet文件中创建一个post.js端点:

'use strict';
 module.exports = function(Post) {
        Post.customGet = function (postId, cb) {
            Post.findOne({where: {id: postId}, include: 'comments'}, function (err, post) {
                if(err){
                    return cb(err, {});
                }
                post.commentCount = post.comments.length;
                return cb(err, post);
            });
        }

        Post.remoteMethod('customGet', {
            description: 'New endpoint with the commentCount',
            accepts: {arg: 'postId', type: 'string'},
            returns: {arg: 'post', type: 'object'},
            http: {verb: 'get'}
        });
  };

您可以稍微改进一下此方法,但您会明白。