如何在环回中自定义PersistedModel?假设我有两个模型Post和Comment。一个帖子hasMany评论,但它最多只能有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
发布于 2018-06-14 10:57:14
我想我找到了一个解决方案。每当您想要覆盖由模型关系创建的方法时,编写一个引导脚本,如下所示:
module.exports = function(app) {
const old = app.models.Post.prototype.__create__comments;
Post.prototype.__create__orders = function() {
// **custom code**
old.apply(this, arguments);
};
};
我认为这是最好的选择。
发布于 2018-06-08 01:07:45
您在这里所问的实际上是使用操作钩子的一个很好的用例,即在粒子中使用beforesave()
。在这里查看更多信息https://loopback.io/doc/en/lb3/Operation-hooks.html#before-save
然而,我对事务部分不是很确定。
为此,我建议使用remote method,它可以让您完全自由地使用loopback的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
}
}
}
}
发布于 2018-06-08 14:10:51
您可以使用可用于每个模型的validateLengthOf()方法作为可验证类的一部分。有关更多详细信息,请参阅Loopback Validation
https://stackoverflow.com/questions/50731977
复制相似问题