javascript - 自定义环回模型
问题描述
如何在环回中自定义 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
解决方案
你在这里问的实际上是使用操作钩子的好用例之一,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
}
}
}
}
推荐阅读
- java - java中的包 - 必要吗?
- mysql - MYSQL如何排除2个不同日期之间的工作日
- php - 使用 AJAX 成功函数将隐藏输入字段的值更改为 PHP 变量
- angular - Angular 7 HttpHeaders 是空的
- amazon-web-services - Elastic Beanstalk 扩展:命令何时完成?
- javascript - 更改 JSON 格式/布局
- javascript - 如何在更新记录时锁定记录以使 NetSuite 上的值保持一致?
- php - 为什么在codeigniter中插入表单后VALUE为NULL?
- list - 获取 Prolog 中的正值列表
- r - 无法将变量传递给 r 中的函数