无法使用来自另一个模块或领域的 GraphQLSchema

Cannot use GraphQLSchema from another module or realm

我正在使用 type-graphqlapollo-server-lambda 构建无服务器后端,但是在对 graphql 端点发出大约第三次请求后我收到错误

Error: Cannot use GraphQLSchema "[object GraphQLSchema]" from another module or realm.

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.

我已经降级了 type-graphql 因为版本 1.0.0 需要 graphql@^15.3.0 而其他一些依赖项需要 graphql <= 14

这是我的依赖项

{
  "dependencies": {
    "@types/graphql": "14.5.0",
    "apollo-server-lambda": "^2.17.0",
    "aws-sdk": "^2.750.0",
    "graphql": "^14.7.0",
    "pg": "^8.3.3",
    "reflect-metadata": "^0.1.13",
    "source-map-support": "^0.5.19",
    "type-graphql": "^0.17.0",
  },
  "devDependencies": {
    "@types/aws-lambda": "^8.10.62",
    "@types/aws-sdk": "^2.7.0",
    "@types/jest": "^26.0.13",
    "@types/node": "^14.10.0",
    "apollo-server-testing": "^2.17.0",
    "serverless": "^2.0.0",
    "serverless-offline": "^6.7.0",
    "serverless-webpack": "^5.3.4",
    "ts-jest": "^26.3.0",
    "ts-loader": "^8.0.3",
    "typescript": "^4.0.2",
    "webpack": "^4.44.1",
    "webpack-node-externals": "^2.5.2"
  },
  "resolutions": {
    "graphql": "^14.7.0",
  },

npm ls graphql 结果

dives-backend@1.0.0
├─┬ @types/graphql@14.5.0
│ └── graphql@14.7.0  deduped
└── graphql@14.7.0 

index.ts

import "reflect-metadata"
import { buildSchemaSync } from "type-graphql"
import { HelloResolver } from "./src/resolvers/example"

const schema = buildSchemaSync({
    resolvers: [HelloResolver],
    validate: false,
})

const server = new ApolloServer({
    schema,
    playground: { endpoint: "/dev/graphql" },
})

export const handler = server.createHandler({
        cors: {
            origin: true,
            credentials: true,
        },
    })

我遇到了类似的问题,并在 typegraphql FAQ 中找到了建议。 npm dedupe 帮我解决了。

我终于找到了解决方案。我将 apollo-server-lambda 升级为 3.0.0-alpha.3,并将 type-graphql 恢复为 ^1.0.0。我还将 resolution 升级为 "graphql": "15.3.0"

将 type-graphql 与 lambda 一起使用时,还有一个重要步骤是覆盖全局对象(名称 schema 很重要)- reference issue

if (!global.schema) {
  global.schema = buildSchemaSync({
    resolvers: [UserResolver],
    validate: false,
  });
}
const schema = global.schema;