首页 > 解决方案 > 自定义环回模型

问题描述

如何在环回中自定义 PersistedModel?假设我有两个模型 Post 和 Comment。一个帖子有很多评论,但它最多可以有 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

标签: javascriptnode.jsloopbackjsangular-loopback

解决方案


你在这里问的实际上是使用操作钩子的好用例之一,beforesave()尤其是。在此处查看更多信息 https://loopback.io/doc/en/lb3/Operation-hooks.html#before-save

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

为此,我建议使用远程方法,它使您可以完全自由地使用环回的事务 API。这里要考虑的一件事是,您必须确保所有注释都是仅通过您的方法创建的,而不是通过默认的环回方法创建的。

然后你可以做这样的事情

// 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
           }

        }
    }
}

推荐阅读