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

标签 javascript node.js reactjs graphql react-apollo

我在两个独立的存储库中有一个 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);
    }
}

但是我在尝试创建扬声器时遇到以下错误:

Uncaught (in promise) Invariant Violation: Schema type definitions not allowed in queries. Found: "InputObjectTypeDefinition"

有什么建议/想法如何做到这一点?

最佳答案

在向 GraphQL 服务发送请求时,您无法定义其他类型,您也不需要 - 只需使用您已经在服务器上定义的类型(在本例中为 ExpertiseInput :

$expertise: ExpertiseInput!

但是,一开始就不需要使用这么多变量:

mutation CreateSpeaker($input: SpeakerInput!) {
  createSpeaker(speakerInput: $input) {
    name
    age
    nationality
    avatar
    expertise {
      title
      domain
    }
  }
}

关于javascript - 对象作为突变 : GraphQL - Apollo - React 中的输入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60027743/

相关文章:

javascript - Aurelia 中第三方库的依赖注入(inject) (di) 范例

javascript - Mongoose 连接到 MongoDB Atlas 的最佳池大小是多少?

javascript - 无法从 aws lambda (java) 读取 json 正文响应。它说可读流

javascript - 使用 Javascript 时的 Mongoose 和查询注入(inject)?

javascript - 预期 onClick 监听器是一个函数,而不是类型对象 - React redux

javascript - react native : invoke method dynamically

javascript - 'keypress' 的 addeventlistener = 验证码替代方案?

javascript - 扩展命名空间 JS 导入

javascript - 仅重新加载 $state.go 的特定 Controller

node.js - 使用 Socket.IO 设置和获取 session 数据时,传递的函数有何用途?