所以我读了很多关于 RESTfull 设计的书——特别是处理资源。
以用户、帖子和评论的典型例子为例,关系如下:
用户 ---(hasMany)---> 发布 ---(hasMany)---> 评论
最初可能会考虑公开以下内容:
GET /users GET /posts GET /comments
POST /users POST /posts POST /comments
GET /users/id GET /posts/id GET /comments/id
PUT /users/id PUT /posts/id PUT /comments/id
DELETE /users/id DELETE /posts/id DELETE /comments/id
但是,假设我想要某个特定用户发表的某个帖子的所有评论。我需要做类似的事情:
GET /users/id
> someUser
> var postIds = someUser.posts()
GET /posts?id=<postIds[0]>&id=<postIds[1]>&...
> somePosts
> **application user inspects posts to see which one they care about**
> var postOfInterest = somePosts[x];
> var postId = postOfInterest.id;
GET /comments?id=postId
> someComments (finally)
假设我只关心它所有者上下文中的帖子或评论。假设不同的资源结构可能(也可能不是?)更自然:
GET /users
POST /users
GET /users/id
PUT /users/id
DELETE /users/id
GET /users/id/posts
POST /users/id/posts
GET /users/id/posts/id
PUT /users/id/posts/id
DELETE /users/id/posts/id
GET /users/id/posts/id/comments
POST /users/id/posts/id/comments
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
对我来说,这可能是对资源的更好表示。然后我需要的是:
GET /users/id/posts
> somePosts
> **application user inspects posts to see which one they care about**
> var postOfInterest = somePosts[x];
> var postId = postOfInterest.id;
GET /users/id/posts/postId/comments
> someComments
与以前的方法相比,这似乎更像是在文件系统中导航——但我根本不知道它是否是 RESTfull(也许这是 REST 试图摆脱的),因为为了访问Comments资源,我需要知道它属于哪个用户和哪个帖子。但前者需要 3 个请求,而后者只需要 2 个。
想法?