2017-03-22 62 views
1

比方說我的查詢看起來像這樣:如何將嵌套解析器添加到模式?

query { 
    post { 
    id 
    user { id, name } 
    } 
} 

和分解圖如下所示:

{ 
    Query: { 
    post: myPostResolverFunc, 
    } 
} 

我怎麼能爲post.user添加額外的「嵌套」解析器? 我試過,但它不工作:

addResolveFunctionsToSchema(schema, { 
    Query: { 
    post: { 
     user: postUserResolveFunc, 
    }, 
    } 
}); 

回答

2

你只需要編寫你的領域解析器。假設你的模式是這樣的:

type Post { 
    id: ID!, 
    user: User 
} 

type User { 
    id: ID!, 
    username: String! 
} 

type Query { 
    post(id: ID!): Post #assuming you want to request a simple post here 
} 

您可以編寫解析器是這樣的:

addResolveFunctionsToSchema(schema, { 
    Post: { 
    user(root) { 
     getUserById(root.user) 
    } 
    } 
    Query: { 
    post(root, args, context) { 
     return getPostById(args.id) 
    } 
    } 
});