我应该返回关联实体或整个实体的ID [英] Should I return id of associated entity or whole entity
问题描述
好的,假设我们有两个实体:个人资料,由id
,名称和〜10个无关字段组成,以及 Post ,由text
组成, title
,它是author
(配置文件).此外,还有资源/feed 返回包含来自不同配置文件的帖子的feed.
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.
所以我有两个选择:
- 在作者中发送完整的个人资料实体
- 发送作者的ID(有一种方法可以分别请求个人资料)
- Send full Profile entity in author
- Send author's id (there is a way to request Profiles separately)
哪种方式更快(就在前端使用而言)并且更方便(RESTy,如果您愿意的话).
Which way is faster (in terms on using it on front end) and more convenient (RESTy, if you like).
推荐答案
显然,仅发送Profile
的id
会更快,因为响应长度更短.
Obviously just sending the id
of Profile
is faster because the response length is smaller.
但是,重要的问题是,每个Post
是否都需要完整的Profile
对象?例如,如果要打印每个Post
的作者姓名,则发送完整的对象更有意义.但是,如果您只想为每个Post
(在前端)提供给作者的链接,那么id
应该就足够了.
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.
对于查询您的Post
的其他服务,只需发送id
并在需要时让他们再次打个电话即可.如有需要,他们总是可以在其末端缓存数据.
For other services that query yours for Post
s 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.
尝试构建您的服务,以使每个呼叫/端点均返回最低裸机数量的数据,以使响应有意义.这可能意味着Post
包含一个精益的Profile
对象,其中仅包含名称,而所有其他无关"字段均被排除.但是,当您直接查询Profile
时,会得到完整的对象.
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.
您还可以具有一个可选的查询参数,在此参数中,调用方可以指定他们只需要id
还是完整的Profile
,这是一种策略
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.
还可以查看 hal+json
规范,它可以为您提供有关如何设计更多可用和透明的REST服务.
Also check out the hal+json
specification, it can give you good ideas about how to design a more usable and transparent REST service.
最重要!端点应仅返回外界可以实际使用并有意义的数据.因此,这意味着如果Profile
的一个/多个字段仅在您的后端使用这些值(例如,用户的密码),则永远不要将其泄漏出去.
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.
这篇关于我应该返回关联实体或整个实体的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!