使用 NextJS 时在 NexusJS 中定义 contextType 的正确方法

Correct way to define contextType in NexusJS while using NextJS

我试图让 Prisma 和 Nexus 与 NextJS 一起工作,但我在定义 GraphQL 模式中的 contextType 时遇到了一些问题。

我这样定义模式:

export const schema = makeSchema({
  types: [Query, User, Mutation],
  contextType: {
    module: require.resolve("./graphql/context"),
    export: "Context",
  },
  plugins: [nexusPrisma({ experimentalCRUD: true })],
  outputs: {
    typegen: path.join(process.cwd(), "generated", "nexus-typegen.ts"),
    schema: path.join(process.cwd(), "generated", "schema.graphql"),
  },
});

通过运行npm run dev启动开发服务器时出现错误。错误如下:

Module not found: Can't resolve './graphql/context'
  46 |   types: [Query, User, Mutation],
  47 |   contextType: {
> 48 |     module: require.resolve("./graphql/context"),
     |            ^
  49 |     export: "Context",
  50 |   },
  51 |   plugins: [nexusPrisma({ experimentalCRUD: true })],

这是 context.ts 文件:

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export interface Context {
  prisma: PrismaClient;
}

export function createContext(): Context {
  return { prisma };
}

我的依赖项是这些:

  "dependencies": {
    "@prisma/client": "^2.13.1",
    "apollo-server-micro": "^2.19.1",
    "next": "latest",
    "nexus": "^1.0.0",
    "nexus-plugin-prisma": "^0.27.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@prisma/cli": "^2.13.1",
    "@types/node": "^12.12.21",
    "@types/react": "^16.9.16",
    "@types/react-dom": "^16.9.4",
    "typescript": "^4.1.3"
  },

我一直在努力寻找解决方案,但现在我卡住了。我认为它可能与 NextJS 及其 Webpack 配置有关,但我完全不了解这些,所以我真的不知道该尝试什么。

感谢任何帮助。

项目树:

root
├─ generated
│  ├─ nexus-typegen.ts
│  └─ schema.graphql
├─ graphql
│  ├─ context.ts
│  └─ schema.ts
├─ interfaces
│  └─ index.ts
├─ next-env.d.ts
├─ package-lock.json
├─ package.json
├─ pages
│  ├─ api
│  │  ├─ graphql.ts
├─ prisma
│  └─ schema.prisma
├─ tsconfig.json

我认为错误出在您为模块提供的路径中。假设您已经在 ./schema.ts 中定义了架构,您的上下文类型应该如下所示,因为它是您需要指定的相对路径

contextType: {
  module: require.resolve("./context"),
  export: "Context",
}

这种方式对我有用:

  contextType: {
    module: path.join(process.cwd(), "graphql", "context.ts"),
    export: "Context",
  }