问题描述
我正在使用type-graphql
和apollo-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
结果
dive[email protected]
├─┬ @types/[email protected]
│ └── [email protected] deduped
└── [email protected]
和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;