简体   繁体   English

使用GraphQL查询从多语言架构中获取本地化数据

[英]Get localized data from multilingual schema with GraphQL query

I have following MongoDB schema. 我有以下MongoDB模式。

Item {
  _id: ObjectId,
  translations: [{
    language: String
    name: String
  }]
}

So my Item instance could look something like this. 所以我的Item实例可能看起来像这样。

{
  _id: ObjectId("5ba3bf09d3121aba3ba2f488"),
  translations: [
  {
    language: "en"
    name: "a Car"
  },
  {
    language: "de",
    name: "der Wagen"
  }]
}

And I want to be able to query my data with specific language with Graphql this way. 我希望能够通过Graphql用特定语言查询我的数据。

{
  item(where: {language: "en"}) {
    name
  }
}

So it would produce nice output with shape like this. 因此,它将产生具有这样形状的漂亮输出。

{
  name: "a Car"
}

Please can you tell me some good practice or nice way I can setup my Graphql resolvers map? 请您告诉我一些好的做法或不错的方法来设置我的Graphql解析器映射吗?

I'm using Apollo Server. 我正在使用Apollo服务器。

Thank you very much! 非常感谢你!

A general solution for a language specific query (with more than one field) could be: 针对特定语言的查询(具有多个字段)的一般解决方案可能是:

  • passing the language parameter to the query resolver 将language参数传递给查询解析器
  • store the language on the resolver context 将语言存储在解析器上下文中
  • use the language from the context wherever needed 在需要的地方使用上下文中的语言

Query: 查询:

query {
  item(language: "en") {
    name
    otherField
  }
}

Resolver: 解析器:

{
  item: (_, { language }, context) => {
    context.language = language;
    return {
      name: (_, context) => getNameByLang(context.language),
      otherField: (_, context) => getOtherByLang(context.language),
    };
  },
}

Or if there's only one translated field: 或者,如果只有一个翻译字段:

query {
  item {
    name(language: "en")
  }
}

so you get the language directly in the name resolver as an argument. 因此您可以直接在名称解析器中获取该语言作为参数。

{
  item: () => ({
    name: ({ language }) => getNameByLang(language),
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从生成的模式中获取简单的 graphql 突变查询? - How to get simple graphql mutation query from generated schema? 从 React 中的 GraphQL 查询中获取数据 - Get the data from GraphQL query in React 如何使用 graphql gatsby 中第一个查询的变量从第二个查询获取数据? - How to get data from the second query using a variable from the first query in graphql gatsby? GraphQL/Apollo 客户端:如果查询是先前查询的子集,则从缓存中获取数据 - GraphQL/Apollo Client: get data from cache if a query is a subset of a previous query 如何从graphql模式获取所有类型的列表? - How can I get list of all types from graphql schema? ReactJS / GraphQL:显示查询数据 - ReactJS/GraphQL: Display data from query GraphQL:查询:无法从MongoDb获取数据 - GraphQL : queries : cannot get data from MongoDb GraphQL /中继架构“无法查询字段...” - GraphQL/Relay Schema “Cannot query field…” Instagram?__a=1 url 不再工作 & graphql/query 获取数据的问题 - Instagram ?__a=1 url not working anymore & problems with graphql/query to get data 无法从我从graphQL获得的数据中获得属性“ allShopifyProduct” - Unable to get property “allShopifyProduct” from the data I get from graphQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM