简体   繁体   English

自定义回送模型

[英]Customize loopback model

How do i customize a PersistedModel in loopback ? 如何在环回中自定义PersistedModel? Let's say i have two models Post and Comment. 假设我有两个模型Post和Comment。 A Post hasMany Comment but it can have at most 3 comments. 帖子有很多评论,但最多只能有3条评论。 How can i implement that without using hooks? 我如何使用钩子来实现呢? Also i need to do it inside a transaction . 我也需要在交易中进行

I'm coming from java and this is how i would do that: 我来自Java,这就是我要这样做的方式:

class Post  {

   void addComment(Comment c) {

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

   }

 }

then i would write a service ... 那我就写服务...

  class PostService {

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

      }

  }

I know i could write something like: 我知道我可以这样写:

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 ? 




      })


}

i want to be able to use it like this: 我希望能够像这样使用它:

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

What you are asking here is actually one of the good use cases of using operation hooks, beforesave() in particatular. 您在这里要问的实际上是使用操作挂钩的好用例之一,特别是beforesave() See more about it here here https://loopback.io/doc/en/lb3/Operation-hooks.html#before-save 在此处查看有关此内容的更多信息https://loopback.io/doc/en/lb3/Operation-hooks.html#before-save

However, I'm not so sure about the transaction part. 但是,我不太确定交易部分。

For that, I'd suggest using a remote method , it gives you complete freedom to use the transaction APIs of loopback. 为此,我建议使用远程方法 ,它给您使用环回事务API的完全自由。 One thing to consider here is that you'll have to make sure that all comments are created through your method only and not through default loopback methods. 这里要考虑的一件事是,您必须确保所有注释仅通过您的方法而不是通过默认的回送方法创建。

You can then do something like this 然后,您可以执行以下操作

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

        }
    }
}

You can use validateLengthOf() method available for each model as part of the validatable class. 您可以将每个模型可用的validateLengthOf()方法用作validateatable类的一部分。 For more details refer to Loopback Validation 有关更多详细信息,请参阅环回验证

i think i have found a solution. 我想我已经找到了解决方案。 whenever you want to override methods created by model relations , write a boot script like this: 每当您想覆盖由模型关系创建的方法时,请编写如下引导脚本:

module.exports = function(app) {

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

};

i think this is the best choice. 我认为这是最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM