是否允许为对象的表示计算对象的属性?
Is it allowed to compute properties of an object for its representation?
我面临以下情况:
我有一个 Post
对象,它通过多对多关系链接到 Comment
对象。一个 Post
最多可以有 2 Comment
标记为 "Top".
我需要公开一个 API 来提供列出 Post 的功能(以及显示 Post 的详细视图,但这个没问题)。问题是,一个 Post
可以有大量的 Comment
s,我不认为自己显示这个表示:
[{
title: "Lorem ipsum",
....
comments: [{
"author": "...",
"comment": ".....",
"top": false
}, ... // repeat a few thousand times
]
},...
]
但是,我知道此 API 的大多数消费者稍后会希望直接显示热门评论,因此我正在考虑公开此表示:
[{
title: "Lorem ipsum",
....
topComments: [{
"author": "...",
"comment": ".....",
}, .... // repeat once more if needed
]
},...
]
这里我选择不显示所有评论,可以通过/posts/ID_OF_POST/comments访问,但是我在"runtime"处计算了一个topComments
属性(这不是在代码中的原始对象中),并显示标记为 top
的评论
是否允许使用业务逻辑进行计算并公开所表示的对象中不存在的 属性?如果稍后,我想添加一个新的 numberOfComments
计算 属性,它仍然可以吗?
提前感谢您的回答
Is it allowed to compute using business logic
当然是。
and expose a property that doesn't exist in the object represented?
我不会return不同的表示,而是使用不同的资源来获取热门评论的集合资源。
GET /posts/{postId}/top-comments
会 return 一组评论,其形式与完整列表中的形式相同,但只包括最靠前的评论。
您还可以对原始集合使用过滤器:
GET /posts/{postId}/comments?top=true
是的,它被允许,它被命名为“transient”或“virtual”属性。
使用 Symfony 框架,您可以像 this 那样做。
希望对您有所帮助!!
我面临以下情况:
我有一个 Post
对象,它通过多对多关系链接到 Comment
对象。一个 Post
最多可以有 2 Comment
标记为 "Top".
我需要公开一个 API 来提供列出 Post 的功能(以及显示 Post 的详细视图,但这个没问题)。问题是,一个 Post
可以有大量的 Comment
s,我不认为自己显示这个表示:
[{
title: "Lorem ipsum",
....
comments: [{
"author": "...",
"comment": ".....",
"top": false
}, ... // repeat a few thousand times
]
},...
]
但是,我知道此 API 的大多数消费者稍后会希望直接显示热门评论,因此我正在考虑公开此表示:
[{
title: "Lorem ipsum",
....
topComments: [{
"author": "...",
"comment": ".....",
}, .... // repeat once more if needed
]
},...
]
这里我选择不显示所有评论,可以通过/posts/ID_OF_POST/comments访问,但是我在"runtime"处计算了一个topComments
属性(这不是在代码中的原始对象中),并显示标记为 top
是否允许使用业务逻辑进行计算并公开所表示的对象中不存在的 属性?如果稍后,我想添加一个新的 numberOfComments
计算 属性,它仍然可以吗?
提前感谢您的回答
Is it allowed to compute using business logic
当然是。
and expose a property that doesn't exist in the object represented?
我不会return不同的表示,而是使用不同的资源来获取热门评论的集合资源。
GET /posts/{postId}/top-comments
会 return 一组评论,其形式与完整列表中的形式相同,但只包括最靠前的评论。
您还可以对原始集合使用过滤器:
GET /posts/{postId}/comments?top=true
是的,它被允许,它被命名为“transient”或“virtual”属性。
使用 Symfony 框架,您可以像 this 那样做。
希望对您有所帮助!!