Apollo / GraphQL:如何获取嵌套元素?

时间:2017-10-25 14:37:33

标签: javascript mongodb graphql apollo-server

这是我的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]"
      }
    ]
  }
}

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码。

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();
    }
}

答案 1 :(得分:0)

我认为问题来自这条线: content: { type: GraphQLString }。尝试将内容提取到另一个GraphQLObjectType,然后将其作为ArticleType字段传递给content

修改

试试这个:

const ContentType = new GraphQLObjectType({
  name: 'content',
  fields: {
    en: { type: GraphQLList },
    it: { type: GraphQLList }
    // ... other languages 
  }
})

答案 2 :(得分:0)

因为您说语言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
    }
  },
})

我想提出的最后一个问题是,您要将article作为Array返回。我建议改变它以返回单个对象。最后但同样重要的是,您的架构看起来像这样:

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 })
        }
      }
    }   
  })
})

这段代码可能有点偏,因为我没有你的数据库来测试它。我认为这是朝着正确方向发展的良好推动力。