【发布时间】:2020-04-08 17:46:56
【问题描述】:
让我们假设一个简单的基于 Spring 的 RESTful API 和一些嵌套资源。
-
User是每个人创建的用于访问 API 的根实体 - 每个
User都可以创建Posts,因此Post没有创建者就无法存在 -
User也可以评论现有的Posts,因此Comment属于Post
对于这个 API,我选择了以下 RESTful 路由:
-
/api/users为User -
/api/users/{userId}/posts为Post -
/api/users/{userId}/posts/{postId}/comments为Comment
关于我的问题,我是否应该验证父资源是否存在?例如对于请求GET /api/users/2/posts/3/comments/7,我是否应该确保实体User(2) 和Post(3) 也存在?我是否还必须确保实体相互关联,并且没有使用任何 x 存在的任意资源?
示例
@PostMapping("/api/users/{userId}/posts/{postId}/comments")
public void create(@PathVariable("userId") Long userId, @PathVariable("postId") Long postId, @RequestBody CommentPayload payload) {
// userService.existsByIdWithPostId(userId, postId); ???
commentService.createForPost(postId, payload);
}
要在数据库中创建评论,userId 完全无关紧要,只需要postId。我是否仍应确保存在userId X 的用户并且有postId Y 的帖子,还是应该忽略它?
如果是,我怎么能优雅地做到这一点?因为像Optional<Comment> findByUserIdAndPostIdAndId(...) 这样不断增长的JPA/Repository 查询似乎不是一个解决方案......然后验证应该在几个查询中进行吗?包含所有父母的 ID 会使实际查询变得非常复杂。此外,标识符必须通过所有层(服务、安全)传递,这使内部 API 变得复杂。
【问题讨论】:
-
@DumiduUdayanga 它们是url参数,不是查询字符串。
标签: java spring spring-boot rest api