0

我试图让 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
4

2 回答 2

1

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

contextType: {
  module: require.resolve("./context"),
  export: "Context",
}
于 2021-01-02T10:23:51.607 回答
0

这种方式对我有用:

  contextType: {
    module: path.join(process.cwd(), "graphql", "context.ts"),
    export: "Context",
  }
于 2021-01-02T14:12:16.200 回答