查询
拦截 GraphQL 查询。
你可以通过定义一个 graphql.query()
处理程序并通过操作名称匹配来拦截 GraphQL 查询:
¥You can intercept a GraphQL query by defining a graphql.query()
handler for it and matching it by the operation name:
graphql.query('ListUsers', () => {
return HttpResponse.json({
data: {
users: [
{ id: '1', name: 'John' },
{ id: '2', name: 'Kate' },
],
},
})
})
上面的请求处理程序将匹配你应用中的以下 GraphQL 查询:
¥The request handler above will match the following GraphQL query made in your application:
query ListUsers {
users {
id
name
}
}
读取原始查询
¥Reading raw query
你可以通过响应解析器参数的 query
属性访问客户端发送的查询定义:
¥You can access the query definition sent by the client via the query
property of the response resolver’s argument:
graphql.query('ListUsers', ({ query }) => {
console.log(query) // "query ListUsers { users { id name } }"
})
如果你计划从其他来源(例如模拟的 GraphQL 模式)解析模拟响应,则读取原始查询会非常方便。你可以在 Schema 优先模拟 部分了解更多关于该方法的信息。
¥Reading the raw query is handy if you plan on resolving the mocked response from a different source, like a mocked GraphQL schema. You can learn more about that approach in the Schema-first mocking.