5

第一次尝试 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
        }
      ]
    }
  ]
}

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

4

2 回答 2

2

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

于 2019-10-30T11:07:26.923 回答
1

我不确定您要进行什么查询。但是为了返回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)
                })
            }
        }
    })
});
于 2019-02-13T20:18:35.123 回答