使用Prisma+GraphQL执行Mutation时遇错误:$_data不能为非输入类型
解决Prisma+GraphQL Mutation中的"Variable '$_data' cannot be non input type"错误
老哥,这个错误我之前踩过一模一样的坑!本质原因是GraphQL严格区分「输出类型(Object Type)」和「输入类型(Input Type)」——你在Mutation里直接用了普通的Link类型作为变量类型,但GraphQL要求Mutation接收的变量必须是Input类型,而Prisma已经帮你自动生成了对应的Input类型,只是你没用到而已。
错误根源拆解
你定义的Link是一个输出类型(用type关键字声明),只能用来作为Query/Mutation的返回值;而Mutation的变量必须是输入类型(用input关键字声明)。Prisma会根据你的datamodel.graphql自动在generated/prisma.graphql里生成诸如CreateLinkInput、UpdateLinkInput这类输入类型,直接用就行。
具体修复步骤
1. 修正本地schema.graphql的Mutation定义
先从Prisma生成的文件里导入对应的Input类型,再在Mutation中使用它:
# import Link, CreateLinkInput from "./generated/prisma.graphql" type Query { info: String! feed: [Link!]! } type Mutation { # 用Prisma自动生成的CreateLinkInput作为变量类型 postLink(data: CreateLinkInput!): Link! }
2. 确保Resolver正确调用Prisma API
Resolver代码要接收这个Input类型的变量,直接传给Prisma的创建方法即可:
// 以Node.js环境的Resolver为例 async function postLink(parent, { data }, ctx, info) { // 直接把符合Input类型的data传给prisma的createLink方法 return ctx.prisma.createLink(data) } export const Mutation = { postLink }
3. 验证Prisma生成的Input类型
如果你的generated/prisma.graphql里没有CreateLinkInput,说明可能没更新Prisma客户端,执行以下命令重新生成:
prisma generate
生成的Input类型大概长这样:
input CreateLinkInput { description: String! url: String! postedBy: CreateOneLinkPostedByInput }
额外提醒
如果需要自定义输入类型(比如加额外校验),别用type,要用input关键字声明,比如:
input CustomPostLinkInput { description: String! url: String! # 自定义额外字段 isPublic: Boolean! }
但绝大多数场景下,直接用Prisma自动生成的Input类型就够了,能避免类型不匹配的问题。
内容的提问来源于stack exchange,提问作者Nomura Nori
相关产品推荐
相关产品推荐

