自定义环回模型

时间:2018-06-07 02:02:44

标签: javascript node.js loopbackjs angular-loopback

如何在环回中自定义PersistedModel?让我们说我有两个模型发布和评论。一篇帖子有很多评论,但它最多可以有3条评论。如何实现不使用使用挂钩?我还需要在交易中进行此操作。

我来自java,我就是这样做的:

class Post  {

   void addComment(Comment c) {

         if(this.comments.size() < 3)
              this.comments.add(c) 
         else 
           throw new DomainException("Comment count exceeded") 

   }

 }

然后我会写一个服务......

  class PostService {

      @Transactional
      public void addCommentToPost(postId, Comment comment) {
             post = this.postRepository.findById(postId); 
             post.addComment(comment)
             this.postRepository.save(post); 

      }

  }

我知道我可以这样写:

module.exports = function(app) {

      app.datasources.myds.transaction(async (models) => {

         post = await models.Post.findById(postId) 
         post.comments.create(commentData); ???? how do i restrict comments array size ? 




      })


}

我希望能够像这样使用它:

// create post 

POST /post --> HTTP 201

// add comments 

POST /post/id/comments --> HTTP 201
POST /post/id/comments --> HTTP 201
POST /post/id/comments --> HTTP 201

// should fail 

POST /post/id/comments --> HTTP 4XX ERROR

3 个答案:

答案 0 :(得分:0)

这里你要问的实际上是使用操作挂钩的一个很好的用例,beforesave()。在这里查看更多相关信息 https://loopback.io/doc/en/lb3/Operation-hooks.html#before-save

但是,我对交易部分不太确定。

为此,我建议使用remote method,它让您完全自由地使用transaction APIs环回。 这里需要考虑的一件事是,您必须确保所有注释都是通过您的方法创建的,而不是通过默认的环回方法。

然后你可以做这样的事情

// in post-comment.js model file    

module.exports = function(Postcomment){

    Postcomment.addComments = function(data, callback) {
        // assuming data is an object which gives you the postId and commentsArray
        const { comments, postId } = data;

        Postcomment.count({ where: { postId } }, (err1, count) => {
          if (count + commentsArray.length <= 10) {
             // initiate transaction api and make a create call to db and callback

           } else {

             // return an error message in callback
           }

        }
    }
}

答案 1 :(得分:0)

您可以将validateLengthOf()方法用于每个模型,作为可验证类的一部分。 有关详细信息,请参阅Loopback Validation

答案 2 :(得分:0)

我想我找到了解决方案。 无论何时想要覆盖模型关系创建的方法,都要编写如下的启动脚本:

module.exports = function(app) {

    const old = app.models.Post.prototype.__create__comments;
    Post.prototype.__create__orders = function() {
      // **custom code**
       old.apply(this, arguments);
    };

};

我认为这是最好的选择。