gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:16:22 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com