You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GraphQL查询报错:必填类型UUID!的变量$userId未提供,求原因?

GraphQL变量未提供错误的原因及修复方案

我尝试使用GraphQL发送查询,期望在resolver中从参数获取userId变量,但出现错误:Variable "$userId" of required type "UUID!" was not provided.

相关代码如下:

Query定义

const Query = new GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: userType,
      description: 'Get user by Id',
      args: {
        id: {
          type: UUIDType,
        },
      },
      resolve: async (_, args: { userId: string }, _context) => {
        try {
        const user = await prisma.user.findUnique({
          where: {
            id: args.userId,
          },
        });
        return user;
      } catch {
        return null;
      }
      },
    }
})

userType定义

export const userType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: { type: new GraphQLNonNull(UUIDType) },
    name: { type: new GraphQLNonNull(GraphQLString) },
    balance: { type: new GraphQLNonNull(GraphQLFloat) },
  })
});

查询语句

query ($userId: UUID!) {
        user(id: $userId) {
            id
            name
            balance
        }
    }

错误原因分析

  1. Resolver参数名不匹配:Query的user字段args里定义的参数是id,但resolver函数中错误地尝试读取args.userId,两者名称不一致,导致传入的$userId变量对应到args.id,但resolver未正确使用该值,同时试图读取不存在的userId参数,引发逻辑混乱。
  2. 变量未实际传入:如果发送查询请求时,没有在变量区域提供$userId的具体UUID值,也会触发该错误,这是GraphQL对必填变量的校验机制导致的。

修复方案

  1. 修正Resolver参数读取逻辑:将resolver中的args.userId改为args.id,与Query定义的参数名保持一致,同时修正类型定义:
resolve: async (_, args: { id: string }, _context) => {
  try {
    const user = await prisma.user.findUnique({
      where: {
        id: args.id,
      },
    });
    return user;
  } catch {
    return null;
  }
},
  1. 确保请求时传入变量值:发送查询时,必须在变量部分提供$userId的具体值,示例如下:
{
  "userId": "123e4567-e89b-12d3-a456-426614174000"
}
  1. 可选优化:强制参数必填:为Query的id参数添加GraphQLNonNull,确保客户端必须传入该参数,提前拦截错误:
args: {
  id: {
    type: new GraphQLNonNull(UUIDType),
  },
},

内容的提问来源于stack exchange,提问作者Оксана

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:24:51