首页 > 解决方案 > 如何为 GraphQL 使用数组模式类型

问题描述

第一次尝试 GraphQL,我希望一个模式类型能够访问另一个模式类型中的对象数组。在将其连接到 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
        }
      ]
    }
  ]
}

我重新格式化了对一系列语言进行硬编码的决心,这可行,但它不起作用。任何建议将不胜感激。谢谢大家的时间。

标签: node.jsexpressgraphqllodashgraphiql

解决方案


我的标签的旧项目有问题。最后,我通过 try and catch 找到了你可以使用这个标签:{type: GraphQLList(GraphQLString)},


推荐阅读