[英]Cannot query field in GraphQL (Platform API, Symfony)
我正在使用 Symfony 和 Platform API 來實現 GraphQL API。 我的目標是根據用戶是否登錄來公開不同的字段。只有當用戶登錄並且是用戶時才應顯示電子郵件。 因此我添加了組 user:read:self。
/**
* @ORM\Column(type="string", length=180, unique=true)
* @Groups({"user:read:self"})
*/
private $email;
然后我實現了一個規范化器,如果用戶登錄,它會將組添加到上下文中:
public function normalize($object, string $format = null, array $context = [])
{
echo "test";
// checks whether the currently logged in user is
// this user
$isCurrentUser = $this->currentUser() == $object;
if ($isCurrentUser) {
$context['groups'][] = 'user:read:self';
}
$context[self::ALREADY_CALLED] = true;
return $this->normalizer->normalize($object, $format, $context);
}
規范化器實際上是為 JSON API 和 GraphQL API 調用的。 這適用於 JSON API:
{
"@context": "/api/contexts/User",
"@id": "/api/users",
"@type": "hydra:Collection",
"hydra:member": [
{
"@id": "/api/users/1",
"@type": "User",
"email": "test@example.com",
"animals": [],
"friends": []
},
{
"@id": "/api/users/2",
"@type": "User",
"animals": [],
"friends": []
}
],
"hydra:totalItems": 2
}
我以 ID 為 1 的用戶身份登錄,我可以看到電子郵件。 我看不到用戶 2 的電子郵件。
然后在 GraphQLi 中,即使我以用戶 1 身份登錄,我也會查詢以下內容並出現錯誤。我檢查了 GraphQL 查詢是否正在調用規范化器。 規范器工作並添加組,但是 GraphQL 似乎沒有正確讀取上下文:
{
user(id: "/api/users/1") {
email
}
}
...
"message": "Cannot query field \"email\" on type \"User\".",
...
簡短的回答:你必須添加一個吸氣劑。
長答案:來自Symfonycast (順便說一句,很棒的課程)實際上有一堆不同的“規范化器”類可以幫助完成這項工作——就像一個非常擅長將 DateTime 對象轉換為字符串並返回的類。 但是主類——這個過程的核心——被稱為 ObjectNormalizer。 在幕后,它使用另一個名為 PropertyAccess 的 Symfony 組件,它有一個超能力:如果你給它一個屬性名稱,比如標題,它真的很擅長查找和使用 getter 和 setter 方法來訪問該屬性。
換句話說,當 API 平台嘗試將對象“規范化”為數組時,它會使用 getter 和 setter 方法來做到這一點!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.