[英]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: 针对特定语言的查询(具有多个字段)的一般解决方案可能是:
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.