简体   繁体   English

使用Relay时本地化GraphQL结果

[英]Localizing GraphQL results when using Relay

I'm hoping someone in the GraphQL/Relay community has encountered this issue. 我希望GraphQL/Relay社区中的某个人遇到过这个问题。

We have a multilingual system, which means that the results are localized. 我们有一个多语言系统,这意味着结果是本地化的。 So we have an argument called lang which is passed down to the field resolvers. 所以我们有一个名为lang的参数,它被传递给字段解析器。

Queries are written as such: 查询是这样写的:

query {
  viewer(lang: ja) {
    books { <- Type is `Book`
      id
      title <- This would be localized to Japanese.
    }
  }
}

Which would return: 哪个会回归:

{
  "data": {
    "viewer": {
      "books": [
        {
          "id": "SOMETHINGSOMETHING123",
          "name": "ハリー・ポッター" // "Harry Potter" in Japanese.
        }
      ]
    }
  }
}

This is possible due to the resolver for translatable fields looking like this (note that I am using dataloader ): 这是可能的,因为可翻译字段的解析器看起来像这样(注意我使用dataloader ):

...
resolve: (parent, args, ast, { rootValue }) => {
  const { language } = rootValue
  const { BookLoader } = rootValue.loaders
  return BookLoader.TranslationsLoader(language).load(parent.id).then(translations => translations[parent.id].title || parent.title)
}

If a translation exists, it will use that instead of the original value. 如果存在翻译,则将使用该翻译而不是原始值。 This was working fine until we introduced Relay into our project. 这一点工作正常,直到我们将Relay引入我们的项目。

We want to utilize Relay's node , and have made it partially work, ie: 我们想要利用Relay的node ,并使其部分工作,即:

query {
  node(id: "SOMETHINGSOMETHING123") {
    ...b
  }
}
fragment b on Book {
  id
  name
}

But since using node can't take arguments like viewer can, there is no way to pass the language. 但由于使用node不能像viewer那样接受参数,因此无法传递语言。

How would I pass language parameters to the resolver which would work with both standard queries and nodes? 如何将language parameters传递给适用于标准查询和节点的解析器?

Since graphql-js v0.6 , each resolver receives a context object as the third parameter. graphql-js v0.6开始 ,每个解析器都接收一个context对象作为第三个参数。 This is good for passing contextual info from the server to GraphQL's execution phase. 这适用于将上下文信息从服务器传递到GraphQL的执行阶段。 We use it, for example, to handle authentication and authorization. 例如,我们使用它来处理身份验证和授权。 You could pass in the desired language there. 你可以在那里传递所需的语言。 If you use express-graphql or koa-graphql , they pass the request object as the context by default. 如果使用express-graphqlkoa-graphql ,默认情况下它们会将request对象作为context传递。 You could examine the headers from the resolver. 您可以检查解析器中的标头。

EDIT: Here is an example of handling a session in a graphql resolver using express-graphql: express-graphql 编辑:这是一个使用express-graphql: express-graphql处理graphql解析器中的会话的示例

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM