Apollo/GraphQL: 如何获取嵌套元素?
Apollo/GraphQL: How to get nested elements?
这是我的 mongoDB 的示例文档。我需要通过 Apollo/GraphQL 获取 content.en
数组。但是嵌套对象对我来说是个问题。
en
是语言标签,如果能作为变量就好了
MongoDB
中的数据
{
"_id" : "9uPjYoYu58WM5Tbtf",
"content" : {
"en" : [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
},
"main" : "Dn59y87PGhkJXpaiZ"
}
graphQL 结果应该是:
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
}
]
}
}
也就是说,我需要获取 ID 和特定于语言的内容数组。
但这不是我通过以下设置得到的结果:
类型
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: { type: GraphQLString }
}
})
GraphQL 模式
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id }).toArray()
}
}
}
})
})
查询
{
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content
}
}
结果
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": "[object Object]"
}
]
}
}
我认为问题来自这一行:
content: { type: GraphQLString }
。尝试将内容提取到另一个 GraphQLObjectType
,然后将其作为 content
字段
传递给 ArticleType
编辑
试试这个:
const ContentType = new GraphQLObjectType({
name: 'content',
fields: {
en: { type: GraphQLList },
it: { type: GraphQLList }
// ... other languages
}
})
既然你说语言 ISO 代码应该是一个参数,并且内容取决于 语言 ISO 代码(我将其称为 languageTag
来自现在开始),我认为您应该将架构编辑为如下所示:
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
},
// Edited this part to add the language tag
languageTag: {
name: 'languageTag',
type: new GraphQLNonNull(GraphQLString)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id }).toArray()
}
}
}
})
})
但是,这仍然不能解决您检索内容的问题。我认为您需要将另一种类型添加到名为 ContentType
.
的架构中
const ContentType = new GraphQLObjectType({
name: 'ContentType',
fields: {
content: {
type: GraphQLString,
resolve: (root, args, context) => root.content[args.languageTag].content
},
timestamp: {
type: GraphQLString,
resolve: (root, args, context) => root.content[args.languageTag].timestamp
}
},
})
我想提出的最后一个问题是,您正在 return 将单个 article
作为 Array
。我建议将其更改为 return 单个对象。最后但同样重要的是,您的架构将如下所示:
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
},
// Edited this part to add the language tag
languageTag: {
name: 'languageTag',
type: new GraphQLNonNull(GraphQLString)
},
// Add the extra fields to the article
fields: {
content: ContentType
}
async resolve ({ db }, args) {
return db.collection('articles').findOne({ main: args.id })
}
}
}
})
})
这段代码可能有点偏差,因为我没有你的数据库来测试它。我认为这是朝着正确方向的一个很好的推动。
您可以使用下面的代码。
String query = {
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content(language:"en") {
content,
timestamp
}
}
}
const ContentType = new GraphQLObjectType({
name: 'content',
fields: {
content: { type: GraphQLString },
timestamp: { type: GraphQLInt }
}
})
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: {
type: new GraphQLList(ContentType),
args: {
language: {
name: 'language',
type: new GraphQLNonNull(GraphQLString)
}
},
async resolve (args) {
return filter content here by lang
}
}
}
}
})
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id}).toArray()
}
}
}
})
})
Java 示例:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.*;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static graphql.Scalars.*;
import static graphql.schema.GraphQLArgument.newArgument;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLSchema.newSchema;
public class GraphQLTest {
private static final ArticleRepository articleRepository;
public static class ArticleRepository {
private final MongoCollection<Document> articles;
ArticleRepository(MongoCollection<Document> articles) {
this.articles = articles;
}
public List<Map<String, Object>> getAllArticles(String id) {
List<Map<String, Object>> allArticles = articles.find(Filters.eq("main", id)).map(doc -> (Map<String, Object>)doc).into(new ArrayList<>());
return allArticles;
}
}
public static void main(String... args) {
String query = "{\n" +
" article(id: \"Dn59y87PGhkJXpaiZ\") {\n" +
" _id,\n" +
" content(language:\"en\") {\n" +
" content,\n" +
" timestamp\n" +
" }\n" +
" }\n" +
"}";
ExecutionResult result = GraphQL.newGraphQL(buildSchema()).build().execute(query);
System.out.print(result.getData().toString());
}
static {
MongoDatabase mongo = new MongoClient().getDatabase("test");
articleRepository = new ArticleRepository(mongo.getCollection("articles"));
}
private static GraphQLSchema buildSchema() {
GraphQLObjectType ContentType = newObject().name("content")
.field(newFieldDefinition().name("content").type(GraphQLString).build())
.field(newFieldDefinition().name("timestamp").type(GraphQLInt).build()).build();
GraphQLObjectType ArticleType = newObject().name("article")
.field(newFieldDefinition().name("_id").type(GraphQLID).build())
.field(newFieldDefinition().name("content").type(new GraphQLList(ContentType))
.argument(newArgument().name("language").type(GraphQLString).build())
.dataFetcher(dataFetchingEnvironment -> {
Document source = dataFetchingEnvironment.getSource();
Document contentMap = (Document) source.get("content");
ArrayList<Document> contents = (ArrayList<Document>) contentMap.get(dataFetchingEnvironment.getArgument("lang"));
return contents;
}).build()).build();
GraphQLFieldDefinition.Builder articleDefinition = newFieldDefinition()
.name("article")
.type(new GraphQLList(ArticleType))
.argument(newArgument().name("id").type(new GraphQLNonNull(GraphQLID)).build())
.dataFetcher(dataFetchingEnvironment -> articleRepository.getAllArticles(dataFetchingEnvironment.getArgument("id")));
return newSchema().query(
newObject()
.name("RootQueryType")
.field(articleDefinition)
.build()
).build();
}
}
这是我的 mongoDB 的示例文档。我需要通过 Apollo/GraphQL 获取 content.en
数组。但是嵌套对象对我来说是个问题。
en
是语言标签,如果能作为变量就好了
MongoDB
中的数据{
"_id" : "9uPjYoYu58WM5Tbtf",
"content" : {
"en" : [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
},
"main" : "Dn59y87PGhkJXpaiZ"
}
graphQL 结果应该是:
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": [
{
"content" : "Third paragraph",
"timestamp" : 1484939404
}
]
}
]
}
}
也就是说,我需要获取 ID 和特定于语言的内容数组。
但这不是我通过以下设置得到的结果:
类型
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: { type: GraphQLString }
}
})
GraphQL 模式
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id }).toArray()
}
}
}
})
})
查询
{
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content
}
}
结果
{
"data": {
"article": [
{
"_id": "9uPjYoYu58WM5Tbtf",
"content": "[object Object]"
}
]
}
}
我认为问题来自这一行:
content: { type: GraphQLString }
。尝试将内容提取到另一个 GraphQLObjectType
,然后将其作为 content
字段
ArticleType
编辑
试试这个:
const ContentType = new GraphQLObjectType({
name: 'content',
fields: {
en: { type: GraphQLList },
it: { type: GraphQLList }
// ... other languages
}
})
既然你说语言 ISO 代码应该是一个参数,并且内容取决于 语言 ISO 代码(我将其称为 languageTag
来自现在开始),我认为您应该将架构编辑为如下所示:
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
},
// Edited this part to add the language tag
languageTag: {
name: 'languageTag',
type: new GraphQLNonNull(GraphQLString)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id }).toArray()
}
}
}
})
})
但是,这仍然不能解决您检索内容的问题。我认为您需要将另一种类型添加到名为 ContentType
.
const ContentType = new GraphQLObjectType({
name: 'ContentType',
fields: {
content: {
type: GraphQLString,
resolve: (root, args, context) => root.content[args.languageTag].content
},
timestamp: {
type: GraphQLString,
resolve: (root, args, context) => root.content[args.languageTag].timestamp
}
},
})
我想提出的最后一个问题是,您正在 return 将单个 article
作为 Array
。我建议将其更改为 return 单个对象。最后但同样重要的是,您的架构将如下所示:
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
},
// Edited this part to add the language tag
languageTag: {
name: 'languageTag',
type: new GraphQLNonNull(GraphQLString)
},
// Add the extra fields to the article
fields: {
content: ContentType
}
async resolve ({ db }, args) {
return db.collection('articles').findOne({ main: args.id })
}
}
}
})
})
这段代码可能有点偏差,因为我没有你的数据库来测试它。我认为这是朝着正确方向的一个很好的推动。
您可以使用下面的代码。
String query = {
article(id: "Dn59y87PGhkJXpaiZ") {
_id,
content(language:"en") {
content,
timestamp
}
}
}
const ContentType = new GraphQLObjectType({
name: 'content',
fields: {
content: { type: GraphQLString },
timestamp: { type: GraphQLInt }
}
})
const ArticleType = new GraphQLObjectType({
name: 'article',
fields: {
_id: { type: GraphQLID },
content: {
type: new GraphQLList(ContentType),
args: {
language: {
name: 'language',
type: new GraphQLNonNull(GraphQLString)
}
},
async resolve (args) {
return filter content here by lang
}
}
}
}
})
export default new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
article: {
type: new GraphQLList(ArticleType),
description: 'Content of article dataset',
args: {
id: {
name: 'id',
type: new GraphQLNonNull(GraphQLID)
}
},
async resolve ({ db }, args) {
return db.collection('articles').find({ main: args.id}).toArray()
}
}
}
})
})
Java 示例:
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.*;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static graphql.Scalars.*;
import static graphql.schema.GraphQLArgument.newArgument;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
import static graphql.schema.GraphQLSchema.newSchema;
public class GraphQLTest {
private static final ArticleRepository articleRepository;
public static class ArticleRepository {
private final MongoCollection<Document> articles;
ArticleRepository(MongoCollection<Document> articles) {
this.articles = articles;
}
public List<Map<String, Object>> getAllArticles(String id) {
List<Map<String, Object>> allArticles = articles.find(Filters.eq("main", id)).map(doc -> (Map<String, Object>)doc).into(new ArrayList<>());
return allArticles;
}
}
public static void main(String... args) {
String query = "{\n" +
" article(id: \"Dn59y87PGhkJXpaiZ\") {\n" +
" _id,\n" +
" content(language:\"en\") {\n" +
" content,\n" +
" timestamp\n" +
" }\n" +
" }\n" +
"}";
ExecutionResult result = GraphQL.newGraphQL(buildSchema()).build().execute(query);
System.out.print(result.getData().toString());
}
static {
MongoDatabase mongo = new MongoClient().getDatabase("test");
articleRepository = new ArticleRepository(mongo.getCollection("articles"));
}
private static GraphQLSchema buildSchema() {
GraphQLObjectType ContentType = newObject().name("content")
.field(newFieldDefinition().name("content").type(GraphQLString).build())
.field(newFieldDefinition().name("timestamp").type(GraphQLInt).build()).build();
GraphQLObjectType ArticleType = newObject().name("article")
.field(newFieldDefinition().name("_id").type(GraphQLID).build())
.field(newFieldDefinition().name("content").type(new GraphQLList(ContentType))
.argument(newArgument().name("language").type(GraphQLString).build())
.dataFetcher(dataFetchingEnvironment -> {
Document source = dataFetchingEnvironment.getSource();
Document contentMap = (Document) source.get("content");
ArrayList<Document> contents = (ArrayList<Document>) contentMap.get(dataFetchingEnvironment.getArgument("lang"));
return contents;
}).build()).build();
GraphQLFieldDefinition.Builder articleDefinition = newFieldDefinition()
.name("article")
.type(new GraphQLList(ArticleType))
.argument(newArgument().name("id").type(new GraphQLNonNull(GraphQLID)).build())
.dataFetcher(dataFetchingEnvironment -> articleRepository.getAllArticles(dataFetchingEnvironment.getArgument("id")));
return newSchema().query(
newObject()
.name("RootQueryType")
.field(articleDefinition)
.build()
).build();
}
}