解决Prisma复合ID场景下暴露DateTime字段为ID的类型错误
解决Prisma复合ID中DateTime字段作为GraphQL ID的类型错误问题
错误原因
controlTime是Prisma的DateTime类型,而exposeID方法要求字段类型必须兼容GraphQL的ID标量(仅支持字符串、数字或可转换为这类类型的值),DateTime类型不满足该兼容要求,因此触发类型错误。
解决方案
不要直接用exposeID暴露controlTime,改用自定义字段的方式,将DateTime转换为字符串(符合GraphQL ID的类型要求)后暴露:
修改CarControl.ts中的controlTime字段定义:
builder.prismaObject('CarControl', { fields: (t) => ({ numberPlate: t.exposeID('numberPlate'), // 替换原来的exposeID为自定义字段 controlTime: t.field({ type: 'ID', resolve: (parent) => parent.controlTime.toISOString(), }), carModel: t.relation('carModel'), carColor: t.relation('carColor'), latitude: t.exposeFloat('latitude'), longitude: t.exposeFloat('longitude'), carInspector: t.exposeString('carInspector'), photoPath: t.exposeString('photoPath'), }) })
补充说明
如果后续需要通过复合ID(numberPlate + controlTime)查询单条CarControl记录,还需要在GraphQL中定义对应的输入类型,示例如下:
// 定义复合ID输入类型 const CarControlWhereUniqueInput = builder.inputType('CarControlWhereUniqueInput', { fields: (t) => ({ numberPlate: t.string({ required: true }), controlTime: t.string({ required: true }), }), }) // 添加单条查询字段 builder.queryField('carControl', (t) => t.prismaField({ type: 'CarControl', args: { where: t.arg({ type: CarControlWhereUniqueInput, required: true }), }, resolve: (query, _parent, args, _ctx) => prisma.carControl.findUnique({ ...query, where: { numberPlate_controlTime: { numberPlate: args.where.numberPlate, controlTime: new Date(args.where.controlTime), }, }, }), }) )
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

