如何为GraphQL使用数组架构类型

时间:2019-02-13 19:40:30

标签: node.js express graphql lodash graphiql

第一次尝试GraphQL,我希望一个Schema Type可以访问另一个Schema Type中的对象数组。在将其连接到MongoDB之前,我正在使用本地数据和lodash进行测试。我在尝试中遇到一些错误。我知道我要走了任何援助将不胜感激。

以下是我的最新尝试。我使用express-graphql访问了GraphQLList,并使用GraphQLID访问了第二个模式。

schema.js

var projects = [
{
    name: "Title 1",
    subtitle: "Subtitle 1",
    summary: "Lorem ipsum....",
    languageId: ["4", "2"],
    id: "1"
},
...

var languages = [
{ name: "Javascript", id: "1" },
{ name: "HTML", id: "2" },
{ name: "CSS", id: "3" },
{ name: "Python", id: "4" },
]
...

const ProjectType = new GraphQLObjectType({
name: 'Project',
fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    subtitle: { type: GraphQLString },
    summary: { type: GraphQLString },
    languages: {
        type: new GraphQLList(GraphQLID),
        resolve(parent, args) {
            console.log(parent)
            return _.find(languages, { id: parent.languageId })
        }
    }
})
});

const LanguageType = new GraphQLObjectType({
name: 'Language',
fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
     })
});

//Root Queries
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
    project: {
        type: ProjectType,
        args: { id: { type: GraphQLID } },
        resolve(parent, args) {

           return _.find(projects, { id: args.id });
        }
    },
    language: {
        type: LanguageType,
        args: { id: { type: GraphQLID } },
        resolve(parent, args) {

            return _.find(languages, { id: args.id })
          }
        }
    }
});

目的是在Graphiql中显示该项目中使用的语言列表,看起来像这样...

    {
    "data": {
    "project": {
      "name": "Project 1"
      languages{
          names{
             "Python"
             "HTML" 
              }
            }
         }
        }
       }

相反,我得到以下信息...

    {
  "errors": [
    {
      "message": "Syntax Error: Expected Name, found }",
      "locations": [
        {
          "line": 7,
          "column": 7
        }
      ]
    }
  ]
}

我重新格式化了对多种语言进行硬编码的解决方法,虽然可以,但是没有功能。任何建议将不胜感激。谢谢大家的时间。

2 个答案:

答案 0 :(得分:0)

我不确定您要查询哪个查询。 但是,为了返回嵌套在Languages中的Projects,您应该更改languages字段的返回类型。

类似的东西:

const ProjectType = new GraphQLObjectType({
    name: 'Project',
    fields: () => ({
        id: {type: GraphQLID},
        name: {type: GraphQLString},
        subtitle: {type: GraphQLString},
        summary: {type: GraphQLString},
        languages: {

            // change this type to LanguageType
            type: new GraphQLList(LanguageType),
            resolve(parent, args) {
                // No need to lodash here
                return languages.filter((language) => {
                    return  parent.languageId.includes(language.id)
                })
            }
        }
    })
});

答案 1 :(得分:0)

我的标签的旧项目有问题。最后,我通过尝试发现它,并抓住了你可以使用它    标签:{type:GraphQLList(GraphQLString)},