Невозможно использовать GraphQLObjectType «Запрос» из другого модуля или области

#express #graphql #apollo-server #prisma #prisma-graphql

#экспресс #graphql #apollo-сервер #prisma #prisma-graphql

Вопрос:

Я использую apollo-server-express для сборки сервера graphql

Мои распознаватели server.js так просты, как это

 const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { importSchema } = require('graphql-import');
const typeDefs = importSchema('./src/schema.graphql');
const prisma = require('./src/prisma');

const server = new ApolloServer({
  typeDefs,
  resolvers: {
    Query: {
       users(parent, args, { prisma }, info) {
        return prisma.query.users(args, info);
      }
    }
  },
  context: ({ req }) => ({ ...req, prisma })
});

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
  

и я получаю эту ошибку при запуске пользовательского запроса

 {
  "errors": [
    {
      "message": "Cannot use GraphQLObjectType "Query" from another module or realm.nnEnsure that there is only one instance of "graphql" in the node_modulesndirectory. If different versions of "graphql" are the dependencies of othernrelied on modules, use "resolutions" to ensure only one version is installed.nnhttps://yarnpkg.com/en/docs/selective-version-resolutionsnnDuplicate "graphql" modules cannot be used at the same time since differentnversions may have different capabilities and behavior. The data from onenversion used in the function from another could produce confusing andnspurious results.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "users"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "Error: Cannot use GraphQLObjectType "Query" 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.",
            "",
            "https://yarnpkg.com/en/docs/selective-version-resolutions",
            "",
            "Duplicate "graphql" modules cannot be used at the same time since different",
            "versions may have different capabilities and behavior. The data from one",
            "version used in the function from another could produce confusing and",
            "spurious results.",
            "    at instanceOf (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql\jsutils\instanceOf.js:28:13)",
            "    at isObjectType (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql\type\definition.js:116:34)",
            "    at TypeInfo.enter (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql\utilities\TypeInfo.js:163:61)",
            "    at Object.enter (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql\language\visitor.js:369:16)",
            "    at Object.visit (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql\language\visitor.js:242:26)",
            "    at replaceFieldsWithFragments (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql-tools\src\transforms\ReplaceFieldWithFragment.ts:67:10)",
            "    at ReplaceFieldWithFragment.transformRequest (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql-tools\src\transforms\ReplaceFieldWithFragment.ts:45:22)",
            "    at D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql-tools\src\transforms\transforms.ts:24:21",
            "    at Array.reduce (<anonymous>)",
            "    at Object.applyRequestTransforms (D:\00. DEVELOPMENT\FULL PROJECTS\social-template-2\node_modules\graphql-binding\node_modules\graphql-tools\src\transforms\transforms.ts:21:21)"
          ]
        }
      }
    }
  ],
  "data": null
}
  

и вот мой package.json

 {
  "name": "social-template-2",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "server": "nodemon --ext js,graphql --exec babel-node server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "apollo-server-express": "^2.17.0",
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "bcryptjs": "^2.4.3",
    "express": "^4.17.1",
    "graphql": "^15.3.0",
    "graphql-import": "^1.0.2",
    "jsonwebtoken": "^8.5.1",
    "prisma-binding": "^2.3.16"
  },
  "devDependencies": {
    "@prisma/cli": "^2.7.1",
    "concurrently": "^5.3.0",
    "nodemon": "^2.0.4"
  }
}
  

У вас есть какие-либо идеи, что здесь может быть не так?

Комментарии:

1. Похоже graphql на несоответствие версии пакета. Не могли бы вы попробовать использовать для этого версию eariler, например 14 , и проверить?

2. @Ryan только что сделал это, установил graphql@14.0.0 => та же ошибка!

3. затем я обнаружил, что ему нужен одноранговый узел для 14.2.1. затем я установил его. теперь у меня есть graphql@14.2.1 и у меня все та же проблема, и я каждый раз удаляю блокировку пакета и npm i снова. Но все та же ошибка!

4. какой результат yarn why graphql ?

Ответ №1:

Вероятно, в ваших node_modules есть другой graphql. попробуйте проверить это с помощью:

 find node_modules -name graphql
  

затем посмотрите в package.json каждого модуля graphql и проверьте, какая версия там.

Наконец, в моем случае помогло просто удалить все пакеты, содержащие graphql, и снова установить их вместе:

 npm uninstall apollo-server apollo-server-express graphql neo4j-driver neo4j-graphql-js

npm install apollo-server apollo-server-express graphql neo4j-driver neo4j-graphql-js --force