对象作为突变中的输入变量:GraphQL-Apollo-React

问题描述 投票:0回答:1

我在两个单独的存储库中都有一个React客户端项目和一个Node.js / GraphQL api。

在我的React应用程序中,我想将一个对象作为变量类型传递给我的变异。这是我的变异的样子:

export const CREATE_SPEAKER = gql`

  input Expertise {
    title: String!
    domain: String!
  }

  mutation CreateSpeaker(
    $name: String!
    $age: String!
    $nationality: String!
    $avatar: String!
    $expertise: Expertise!
  ) {
    createSpeaker(
      speakerInput: {
        name: $name
        age: $age
        nationality: $nationality
        avatar: $avatar
        expertise: $expertise
      }
    ) {
      name
      age
      nationality
      avatar
      expertise {
        title
        domain
      }
    }
  }
`;

在我的Node.js项目中,我具有以下架构:

input SpeakerInput {
      name: String!
      age: String!
      expertise: ExpertiseInput!
      nationality: String!
      avatar: String
}

input ExpertiseInput {
      title: String!
      domain: String!
}

和我的解析器:

createSpeaker: async args => {
    const { name, age, nationality, avatar, expertise } = args.speakerInput;

    const newSpeaker = new Speaker({
      name,
      age,
      nationality,
      avatar,
      expertise: {
        title: expertise.title,
        domain: expertise.domain
      }
    });

    try {
      return await newSpeaker.save();
    } catch (error) {
      throw ("Failed to create speaker:: ", error);
    }
}

但是尝试创建扬声器时出现以下错误:

未捕获(承诺)的不变违反:没有架构类型定义在查询中允许。找到:“ InputObjectTypeDefinition”

任何建议/想法如何执行?

javascript node.js reactjs graphql react-apollo
1个回答
0
投票

[向GraphQL服务发送请求时,您无法定义其他类型,并且您不需要-只需使用服务器上已经定义的类型(在这种情况下为ExpertiseInput

$expertise: ExpertiseInput!

但是,首先不需要使用这么多的变量:

mutation CreateSpeaker($input: SpeakerInput!) {
  createSpeaker(speakerInput: $input) {
    name
    age
    nationality
    avatar
    expertise {
      title
      domain
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.