[英]Using graphql fragments in apollo react client
我正在構建一個反應本機應用程序(使用打字稿),其中我使用@apollo/client
v3。 我有許多突變和查詢,它們都返回相同的類型,我總是希望收到相同的字段。 因此,我為模式定義(在客戶端)提出了以下結構:
import { gql } from "@apollo/client";
gql`
fragment ConversationFragment on Conversation {
roomId
name
isDirect
participants {
id
isAdmin
isCreator
membership
}
imageBlurhash
eventIds {
eventId
}
}
`;
export const MUTATE_CONVERSATION_DIRECT_INITIATE = gql`
mutation conversationDirectInitiate($participantId: UUID!) {
conversationDirectInitiate(participantId: $participantId) {
...ConversationFragment
}
}
`;
export const MUTATE_CONVERSATION_DIRECT_DELETE = gql`
mutation conversationDirectDelete($conversationId: UUID!) {
conversationDirectDelete(conversationId: $conversationId) {
delete
conversation {
...ConversationFragment
}
}
}
`;
... many more mutation and queries like the one above
如您所見,我盡量避免重新輸入要返回的字段。 也許還有另一種方法可以達到這個結果?
但是,服務器響應錯誤:
{
"errors": [
{
"message": "Unknown fragment \"ConversationFragment\".",
"locations": [
{
"line": 3,
"column": 8
}
],
"extensions": {
"code": "GRAPHQL_VALIDATION_FAILED",
"exception": {
"stacktrace": [
"GraphQLError: Unknown fragment \"ConversationFragment\".",
" at Object.FragmentSpread (/node_modules/graphql/validation/rules/KnownFragmentNames.js:29:29)",
" at Object.enter (node_modules/graphql/language/visitor.js:324:29)",
" at Object.enter (node_modules/graphql/language/visitor.js:375:25)",
" at visit (node_modules/graphql/language/visitor.js:242:26)",
" at Object.validate (node_modules/graphql/validation/validate.js:73:24)",
" at validate (node_modules/apollo-server-core/src/requestPipeline.ts:513:14)",
" at Object.<anonymous> (node_modules/apollo-server-core/src/requestPipeline.ts:296:32)",
" at Generator.next (<anonymous>)",
" at fulfilled (node_modules/apollo-server-core/dist/requestPipeline.js:5:58)",
" at processTicksAndRejections (internal/process/task_queues.js:97:5)"
]
}
}
}
]
非常感謝您的幫助,非常感謝您!
在每個文檔的末尾插入要使用的片段。
import { gql } from "@apollo/client";
const CONVERSATION_FRAGMENT = gql`
fragment ConversationFragment on Conversation {
roomId
name
isDirect
participants {
id
isAdmin
isCreator
membership
}
imageBlurhash
eventIds {
eventId
}
}
`;
export const MUTATE_CONVERSATION_DIRECT_INITIATE = gql`
mutation conversationDirectInitiate($participantId: UUID!) {
conversationDirectInitiate(participantId: $participantId) {
...ConversationFragment
}
}
${CONVERSATION_FRAGMENT}
`;
export const MUTATE_CONVERSATION_DIRECT_DELETE = gql`
mutation conversationDirectDelete($conversationId: UUID!) {
conversationDirectDelete(conversationId: $conversationId) {
delete
conversation {
...ConversationFragment
}
}
}
${CONVERSATION_FRAGMENT}
`;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.