是否可以像apolloclient那样在react查询中模拟GaphQL请求中的模式字段



我正在迁移我的应用程序以从apolloclient响应查询。对于apolloclient,我正在嘲笑这里显示的模式。以下是它的样子:

const users = [
{
name: "user1name",
image: "https://user1image.jpg",
},
{
name: "user2name",
image: "https://user2image.jpg",
},
{
name: "user3name",
image: "https://user3image.jpg",
},
{
name: "user4name",
image: "https://user4image.jpg",
},
];
const cache = new InMemoryCache({
typePolicies: {
Post: {
fields: {
user: {
read() {
return user[Math.floor(Math.random() * people.length)];
},
},
},
},
},
});

然后,在对posts的查询中,我可以在user字段后面添加@client,它将运行上面指定的read函数并返回该字段的值,而其他字段将具有来自后端的数据。

我还没有找到任何关于如何使用react查询进行类似操作的信息。这可能吗?

react查询不是一个graphql特定的库,因此任何与架构相关的事情都无法由它处理。react查询基本上想要从queryFn返回一个已解决或已拒绝的Promise-仅此而已。

所以这个问题可能更多地与您实际使用make the graphql请求的库有关,比如graphql请求或urql-core?

您始终可以做的是在queryFn中提取数据之后,但在从useQuery返回数据之前,修改数据。如果您查看文档中的graphql基本示例,您可以执行以下操作:

useQuery("posts", async () => {
const {
posts: { data },
} = await request(
endpoint,
gql`
query {
posts {
data {
id
title
}
}
}
`
);
return {
...data,
someOtherField: myMockedOtherFieldData };
}
});

最新更新