我对用户实体“/users/me”有一个自定义的 Get 操作,这是我的第一个操作。因此,它比用于检索特定用户的“/users/{id}”操作更快匹配。
但是现在,GetCollection "/users" 中的每个用户都有 {"@id": "/users/me"}
如果我将“/users/me”的顺序与“/users/{id}”交换,那么“/users”工作正常,但是对于“/users/me”我得到一个未找到的异常,因为用户显然,ID 为“我”的不存在。
默认情况下,API平台使用定义的第一个Get操作来生成一个项目的IRI,第一个GetCollection操作来生成一个集合的IRI。
https://api-platform.com/docs/core/controllers/
有什么方法可以覆盖某个集合操作的默认行为吗?
我已经尝试命名我的路线,并试图从获取操作类属性中找出一种方法,该属性可以覆盖“第一个操作默认”但我未能在文档或代码中找到它。
我是否有任何其他选择来保留“/users/me”,或者我是否必须忘记使用“/users/me”作为端点而使用其他东西?
谢谢
#[ApiResource(
operations: [
new Get(
uriTemplate: '/users/me',
controller: UserBasicInfo::class,
description: 'Get the current user basic information.',
normalizationContext: [
'groups' => ['user:me:get'],
],
security: "is_granted('IS_AUTHENTICATED_FULLY')",
securityMessage: 'Access denied.',
read: false,
write: false,
name: "api_users_get_self",
),
new Get(
normalizationContext: [
'groups' => ['user:get'],
],
security: "is_granted('IS_AUTHENTICATED_FULLY')",
securityMessage: 'Access denied.',
read: true,
name: "api_users_get_item",
),
new GetCollection(
normalizationContext: [
'groups' => ['user:get:collection'],
],
security: "is_granted('IS_AUTHENTICATED_FULLY')",
securityMessage: 'Access denied.',
),
...
],
paginationEnabled: true,
)]
用 GetCollection 替换 '/users/me' 端点的 Get 操作:
#[ApiResource(
operations: [
new GetCollection(
uriTemplate: '/users/me',
controller: UserBasicInfo::class,
description: 'Get the current user basic information.',
normalizationContext: [
'groups' => ['user:me:get'],
],
security: "is_granted('IS_AUTHENTICATED_FULLY')",
securityMessage: 'Access denied.',
read: false,
write: false,
name: "api_users_get_self",
),
...
],
paginationEnabled: true,
)]
@Aymeric 发布的解决方案工作正常,但它在文档生成方面有一些缺点。
我正在试验并想到一个想法,如果我首先使用
/users/{id}
操作,那么它作为默认值工作,但显式添加 uriTemplate 并将 {id} 的要求设置为数字,那么 /users/{id}
应该与 /users/me
不匹配,它应该继续进行自定义 /users/me
操作。
/users/me
的回答是正确的new Get(
uriTemplate: '/users/{id}',
requirements: ['id' => '\d+'],
normalizationContext: [
'groups' => ['user:get'],
],
),
new Get(
uriTemplate: '/users/me',
controller: UserBasicInfo::class,
description: 'Get the current user basic information.',
normalizationContext: [
'groups' => ['user:me:get'],
],
),
new GetCollection(
normalizationContext: [
'groups' => ['user:get:collection'],
],
),
如果我对文档的理解是正确的,那么您的 GetCollection 中的这个选项正是您的场景:
itemUriTemplate: '/users/{id}'
https://api-platform.com/docs/core/operations/#defining-which-operation-to-use-to-generate-the-iri