要更新AWS Graphql API的DataStore,需要在mutation resolver中调用DataStore中更新方法,例如AWS Amplify中的API.update。以下是示例代码:
import { API } from 'aws-amplify';
const updatePost = `
mutation updatePost($input: UpdatePostInput!) {
updatePost(input: $input) {
id
title
content
createdAt
}
}
`;
const updatePostResolver = async (_, { input }, { cache }) => {
// 调用API.update来更新DataStore中的数据
await API.update('MyApiName', '/posts', {
body: input,
});
// 更新GraphQL缓存
const data = cache.readQuery({
query: getPosts,
});
const newData = { ...data };
newData.getPosts.items = newData.getPosts.items.map((post) => {
if (post.id === input.id) {
return { ...post, ...input };
}
return post;
});
cache.writeQuery({
query: getPosts,
data: newData,
});
return input;
};
export { updatePost, updatePostResolver };
在上面的代码中,mutation resolver通过调用API.update
方法来更新DataStore中的数据,然后更新GraphQL缓存以反映更新后的数据。这样,当查询获取更新后的数据时,将返回最新的数据。