我有一个传统的REST API,它返回如下数据:
GET /users.json
users: [
{id: 0, name: "John Smith"},
...
]
GET /users/0.json
user: {
id: 0,
name: "John Smith"
}
如您所见,如果您首先从列表中请求数据(/users.json
),然后单击某个用户,即使该信息出现在第一个列表中,也会从该列表中重新请求用户通过id请求。
在Falcor中,这可以通过在第一次调用中提供参考列表来解决。
我的问题是,如果我正在编写Falcor路由器作为中间人,我该如何优化这种情况?目前,路由器必须请求完整的用户列表,然后丢弃信息并将基于ID的引用列表返回给客户端。这仍然节省了客户端的带宽,但在Falcor路由器及其数据源(REST API)之间并不是最理想的。
答案 0 :(得分:0)
It is possible to workaround this situation, but first, I would like to explain why you are seeing this mismatch. It is because Falcor respect REST principles, but your API does not. REST states that data coming from the API should be cacheable. It cannot be cacheable if it resides in two places at once. For example, if I were to PUT
or PATCH
/users/0.json
, how can the client know that this operation has an impact on /users.json
(a different resource) and invalidate its cache? It cannot. In fully-compliant HTTP REST APIs and Falcor APIs alike, data resides in one place only, and then it can be linked to via refs. For HTTP, refs are URLs, and so a GET
call to /users.json
should respond with a list of URLs like ["/users/0.json", "/users/1.json"]
.
That said, it does not mean you are out of luck.
What you probably want on the Falcor side is to have a route like this: users[{integers:indices}][{keys:props}]
. In the handler for this route, you can query pathSet.indices
and see how much indices were actually requested. If there is only one (or few), forward the request to /users/${indices[i]}.json
, otherwise forward it to /users.json
.