问题描述
好的,假设我们有两个实体: profile ,由id,名称和〜10无关字段组成, post ,由text组成, title,它是author(配置文件).此外,还有资源/feed 返回包含不同配置文件的帖子的exp.
所以我有两个选项:
- 发送完整 profile 实体在作者
- 发送作者的ID(有一种方法可以单独请求配置文件)
哪种方式更快(在前端使用它)和更方便(Resy,如果您喜欢).
推荐答案
显然只需发送Profile的id更快,因为响应长度较小.
但是,重要的问题是您需要每个Post的完整Profile对象吗?例如,如果要打印出每个Post的作者的名称,则发送完整对象更有意义.但是,如果你想用每个Post(前端在前端)提供给作者的链接,那么id应该足够.对于查询Post s的其他服务只是发送id,如果需要,请使它们进行第二个电话.如果需要,它们总是可以将数据缓存到最后.
尝试构建您的服务,以便每个呼叫/端点都返回<强>裸机最小值响应感所所需的数据量.这可能意味着Post包含一个lean Profile对象,其中仅包括名称,但所有其他"无关",字段被排除在外.但是直接查询Profile时,可以获得完整的对象.
您还可以有一个可选的查询参数,其中调用者可以指定它们是否只想要id或完整Profile,这是一个策略 atlassian jira 用于保留带宽并提高速度.
还看看 hal+json 规格,它可以为您提供如何设计的良好想法更具可用且透明的休息服务.
最重要的!您的端点只能返回外部世界实际使用和理解的数据.因此,如果Profile具有字段/字段,则仅在后端使用的字段/字段(例如,例如用户的密码),那么您应该永远不会泄漏那些.
问题描述
OK, lets assume we have two entities: Profile, consisting of id, name and ~10 irrelevant fields, and Post, consisting of text, title, and it's author (Profile). Also, there is resource /feed that returns feed containing posts from different profiles.
So I have two options:
- Send full Profile entity in author
- Send author's id (there is a way to request Profiles separately)
Which way is faster (in terms on using it on front end) and more convenient (RESTy, if you like).
推荐答案
Obviously just sending the id of Profile is faster because the response length is smaller.
The important question, however, is do you need the full Profile object with each Post? If you want to, for example, print out the name of the author for each Post then sending the full object makes more sense. But if you want to just supply a link to the author with each Post (in the front end) then the id should be enough.
For other services that query yours for Posts just send the id and have them make a second call if they need. They can always cache the data on their end if needed.
Try to build your service so that each call/endpoint returns the bare minimum amount of data needed to make sense of the response. This might mean that a Post contains a lean Profile object where only the name is included but all the other, "irrelevant", fields are excluded. But when you query a Profile directly, you get the full object.
You can also have an optional query parameter where the caller can specify whether they want just the id or the full Profile, this is a strategy Atlassian JIRA uses to preserve bandwidth and improve speed.
Also check out the hal+json specification, it can give you good ideas about how to design a more usable and transparent REST service.
MOST IMPORTANT! Your endpoints should only return data that the outside world can actually use and make sense of. So that means if Profile has a field/fields which values are only used in your back-end (like, for example, the user's password) then you should never leak those out.