我有一个返回两个字段的 GraphQL 查询,titleDe
和 titleFr
,代表两种不同语言的帖子标题。
我想在客户端有第三个字段(因此可能是本地状态定义的)以在 title
中存储当前语言的标题。然后,我的应用程序应该能够始终仅调用 title
并获取当前语言的标题。
在 Apollo(本地状态)或 GraphQL 中是否有等效的计算字段,这将允许我调用 title
,它检查在 Apollo Local State 中全局设置的语言环境(所以另一个查询)和然后根据那个返回 titleDe
或 titleFr
?
我还没有太多地使用 GraphQL 和 Apollo。我知道如何在其他本地状态管理器中解决这个问题,例如NgRx、Vuex、Redux 以及 getters/selectors 的概念。
我的目标是从我的应用程序组件中抽象出 titleDe/Fr 逻辑,因此它们不需要具有所有语言属性的模型,并且只能调用简化的 title
属性,它将返回基于全局设置语言环境的正确字符串。
最佳答案
您可以使用 Apollo 本地状态轻松添加其他字段。来自docs :
Local resolvers are very similar to remote resolvers. Instead of sending your GraphQL query to a remote GraphQL endpoint, which then runs resolver functions against your query to populate and return a result set, Apollo Client runs locally defined resolver functions against any fields marked with the @client directive.
这是一个简单的例子:
const GET_LOCALE = gql`
query GetLocale {
locale @client
}
`;
const client = new ApolloClient({
cache,
link,
resolvers: {
Article: { // or whatever your actual type is called
title: (article, _args, { cache }) => {
const { locale } = cache.readQuery({ query: GET_LOCALE });
switch (locale) {
case 'de': return article.titleDe
case 'fr': return article.titleFr
}
},
},
},
});
// Initialize the cache after creating it
cache.writeData({
data: {
locale: getPreferenceOrProvideDefault(),
},
});
这里我们也将 locale
存储在本地状态中,并使用 readQuery
在我们的解析器中获取它。但是,您也可以直接从其他地方(例如 localStorage
)获取首选项。
请注意,您仍然需要在查询中请求这些字段——即您的 title
字段将不会扩展为适当的服务器端字段集。
关于graphql - GraphQL Schema 上的计算字段或使用 Apollo Client 进行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56073110/