Type-GraphQL中定义JSON类型字段使用Prisma相关类型报错如何解决
TypeGraphQL + Prisma 自定义JSON输入字段解决方案
报错原因
Prisma提供的Prisma.JsonValue、Prisma.JsonObject都属于编译阶段的TypeScript类型,没有对应的运行时GraphQL标量实现,TypeGraphQL无法直接将其识别为合法的GraphQL字段类型,因此直接用来定义@Field会抛出类型不匹配错误。
具体实现步骤
- 第一步:安装
graphql-scalars依赖,该包提供了官方认可的JSON、JSONObject等GraphQL标量实现
npm install graphql-scalars # 或使用pnpm pnpm add graphql-scalars # 或使用yarn yarn add graphql-scalars
- 第二步:在输入类型定义中显式指定字段的GraphQL标量
import { InputType, Field } from 'type-graphql'; // 引入对应标量 import { GraphQLJSON, GraphQLJSONObject } from 'graphql-scalars'; import { Prisma } from '@prisma/client'; @InputType() export class YourInputType { // 如果允许任意JSON类型(数组、对象、基础类型等),用GraphQLJSON @Field(() => GraphQLJSON) anyJsonField: Prisma.JsonValue; // 如果仅允许JSON对象类型,用GraphQLJSONObject @Field(() => GraphQLJSONObject) objectJsonField: Prisma.JsonObject; }
- 第三步:Resolver中直接传递参数给Prisma操作即可,无需额外类型转换
@Mutation(() => YourBusinessModel) async addData(@Arg('input') input: YourInputType) { return prisma.yourBusinessModel.create({ data: { anyJsonField: input.anyJsonField, objectJsonField: input.objectJsonField } }) }
注意事项
- 不要省略
@Field的类型参数,TypeGraphQL无法从TypeScript类型推断出运行时的JSON标量,必须显式传入() => GraphQLJSON - 如果你的Prisma Schema中对应字段配置了
nullable: true,需要在@Field参数中添加nullable: true,TS类型也对应改为可选类型或者Prisma.JsonValue | null
内容的提问来源于stack exchange,提问作者Minor Vargas
相关产品推荐
相关产品推荐

