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

Nexus+Prisma+TS项目中Resolver上下文未类型化问题求助

Nexus Resolver上下文类型缺失问题解决

问题现象

搭建Nexus + Prisma + TypeScript API时,Resolver中的上下文参数无法获取类型,prisma被识别为any类型,VS Code无代码自动补全功能。

解决步骤

1. 确保Nexus类型生成已执行

Nexus需要根据makeSchema配置生成类型定义文件,若未自动生成,手动执行以下命令:

npx nexus generate

或者运行项目启动命令(如npm run dev),Nexus通常会在开发模式下自动生成类型。

2. 验证contextType配置正确性

检查src/graphql/schema.ts中的contextType配置,确保路径和导出名称正确指向你的Context接口:

export const schema = makeSchema({
    types: allTypes,
    outputs: {
        schema: path.join(process.cwd(), "nexus", "schema.graphql"),
        typegen: path.join(process.cwd(), "nexus", "nexus.ts"),
    },
    contextType: {
        // 确保路径正确指向context.ts文件
        module: path.join(process.cwd(), "src/context.ts"),
        export: "Context", // 对应context.ts中导出的接口名称
    },
})

3. 在Resolver中显式指定上下文类型

Nexus会在nexus/nexus.ts中生成与Context关联的类型,在Resolver文件中导入该类型并指定给上下文参数:

// src/graphql/user.ts
import { Context } from '../../nexus/nexus'; // 导入生成的Context类型
import { queryField, nonNull, intArg, nullable } from 'nexus';
import { UserType } from './types';
import { User } from '@prisma/client';

export const getUser = queryField("getUser", {
    type: nullable(UserType),
    args: {
        id: nonNull(intArg()),
    },
    resolve: (
        _, 
        { id }: Pick<User, "id">,
        { prisma }: Context // 显式指定上下文类型
    ) => prisma.user.findFirst({ where: { id } }),
})

4. 额外检查

  • 确保已执行npx prisma generate生成Prisma Client的类型定义
  • 若Apollo Server的上下文配置为函数(而非对象),确保函数返回值符合Context接口:
    // src/index.ts
    const apolloServer = new ApolloServer({
        schema,
        context: () => ({ prisma }), // 函数形式需返回符合Context的对象
    })
    

内容的提问来源于stack exchange,提问作者Tiago Brandão

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:54:21