Cannot use GraphQLObjectType \"Query\" from another module or realm - express

I am using apollo-server-express to build graphql server
My resolvers in server.js is as simple as that
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}`)
);
and i am getting this error when i run users query
{
"errors": [
{
"message": "Cannot use GraphQLObjectType \"Query\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious 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
}
and here is my 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"
}
}
Do you have any idea what could be wrong here ?

There is probably another graphql in your node_modules.
try to check it with:
find node_modules -name graphql
then look in package.json of each graphql modules and check what version is there.
Finally, what helped in my case is just uninstalling all packages that contain graphql and install them again together:
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

Related

inject is not defined - CodeceptJs and CucumberJs

It's my first time using CodeceptJs and I'm struggling to run my feature file as the IDE asks me to implement steps for my scenario but this is already done, so I feel it may be searching for them somewhere other than the specified under the codecept.conf.js file?
When I run npx codeceptjs gherkin:steps or snippets on the terminal I get this message saying Could not include object Step Definition from ./step_definitions/steps.js from module '/Users/myUser/IdeaProjects/codeceptjs_webdriver/step_definitions/steps.js' The "from" argument must be of type string. Received undefined .
I then move the step_definitions folder to inside features as read that this would be the default location for these and now get an inject is not defined error, which may be the actual cause for the issue I'm getting, but not sure what to do to fix it.
I've tried on IntelliJ Ultimate, Webstorm and VSCode but get the same on all of them.
basic.feature
Feature: Business rules
In order to achieve my goals
As a persona
I want to be able to interact with a system
Scenario: do something
Given I have a defined step
steps.js
const {Given} = require('cucumber');
const {I} = inject();
Given(/^I have a defined step$/, function () {
I.amOnPage('/');
});
codecept.conf.js
exports.config = {
output: './output',
helpers: {
WebDriver: {
url: 'https:www.google.com',
browser: 'chrome'
}
},
include: {
I: './steps_file.js'
},
mocha: {},
bootstrap: null,
teardown: null,
hooks: [],
gherkin: {
features: './features/*.feature',
steps: ['./step_definitions/steps.js']
},
plugins: {
screenshotOnFail: {
enabled: true
},
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
}
},
tests: './*_test.js',
name: 'codeceptjs_webdriver'
}
package.json
{
"name": "codeceptjs_webdriver",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"codeceptjs": "^3.0.0",
"cucumber": "^5.0.1"
},
"dependencies": {
"#codeceptjs/configure": "^0.6.0"
},
"description": ""
}
IntelliJ Ultimate 2020.2
And here my Github repo
Thank you very much.
It's working now and I've come back to update it here if useful to someone else.
Was able to keep the steps under step_definitions/steps folder (not the one inside the features folder). To fix the non implemented issue had to install the wdio dependency. In order for this to take effect properly through running npm install both node_modules and package-lock.json had to be deleted to be freshly regenerated.
updated package.json
{
"name": "codeceptjs_webdriver",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "npx codeceptjs run"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {},
"dependencies": {
"#wdio/selenium-standalone-service": "^6.6.2",
"codeceptjs": "^2.6.8",
"codeceptjs-assert": "0.0.4",
"webdriverio": "6.3.6"
},
"description": ""
}
updated codecept.conf.js
exports.config = {
output: './output',
helpers: {
WebDriver: {
url: 'https://www.google.com',
browser: 'chrome'
}
},
include: {
I: './steps_file.js'
},
mocha: {},
bootstrap: null,
teardown: null,
hooks: [],
gherkin: {
features: './features/*.feature',
steps: ['./step_definitions/steps.js']
},
plugins: {
wdio: {
enabled: true,
services: ['selenium-standalone']
// additional config for service can be passed here
},
screenshotOnFail: {
enabled: true
},
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
},
tests: './*_test.js',
name: 'codeceptjs_webdriver'
}

db-migrate with #babel/register and ES6 modules - "SyntaxError: Unexpected token export" error

Really hoping someone can help me with this as it's driving me crazy.
Node v12.4.0
package.json: -
{
"name": "#mypackage/db-migrate",
"private": true,
"version": "1.0.0",
"main": "index.js",
"license": "ISC",
"workspaces": {
"packages": [
"common/models"
]
},
"dependencies": {
"#babel/core": "^7.6.0",
"#babel/preset-env": "^7.6.0",
"#babel/register": "^7.6.0",
"#mypackage/models": "1.0.0",
"db-migrate-mysql": "^1.1.10",
"db-migrate-plugin-babel": "^2.0.1",
"npm-upgrade": "^2.0.2"
}
}
.babelrc: -
{
"presets": [
"#babel/preset-env"
]
}
Directory structure: -
common->models - this contains the source lib for #mypackage/models
migrations - contains all the migration files
Yarn installs all the dependencies without issue.
So when I run a migration command ("db-migrate down -c 1", for example), I get the following: -
export { CONSTANT_ONE, CONSTANT_TWO, CONSTANT_THREE };
^^^^^^
SyntaxError: Unexpected token export
This is happening when I am trying to export/import from one of the #mypackage/models files.
var CONSTANT_ONE = "foo_one";
var CONSTANT_TWO = "foo_two";
var CONSTANT_THREE = "foo_three";
export { CONSTANT_ONE, CONSTANT_TWO, CONSTANT_THREE };
Is this a root directory issue? I am complete baffled and utterly frustrated. Any help VERY welcome.
Solved by changing .babelrc to babel.config.js.

The reason why the local API server's "post" is not working even though its "get" is working

Right now I'm trying to build an app as coding training, which involves communication between two different local hosts, whose port numbers are 8080 and 3000.
8080 is the one that is responsible for handling the main functionalities like displaying the content, taking inputs from the users etc, and 3000 is the one that functions as API server.
It didn't seem like some of the requests from 8080 were properly handled by 3000, so I thought of examining how the 3000 (the local API server) works by itself.
Then I began to suspect if this local API server (3000) is partially buggy, because its post doesn't seem to be working while its get does seem to be working.
Here is the configuration.
[api.js]
const fs = require('fs');
const path = require('path');
const express = require('express');
const api = express();
const apiUrl = process.env.URL || 'http://localhost';
const apiPort = 3000;
api.use(express.json());
api.get('/api/feed/get' , (req, res) => {
console.log('Displaying the result of api.get: ');
let feedFile = path.resolve(__dirname, '../feed.json');
res.type('json');
res.sendFile(feedFile);
});
api.post('/api/feed/post' , (req, res) => {
let feedFile = path.resolve(__dirname, '../feed.json');
let feedContent = JSON.parse(fs.readFileSync(feedFile));
let feedPosted = req.body;
let feedJson = '';
console.log('/api/feed/post:', feedPosted);
feedContent.push(feedPosted);
feedJson = JSON.stringify(feedContent);
fs.writeFileSync(feedFile, feedJson);
res.type('json');
res.sendFile(feedFile);
});
api.listen(apiPort, () => {
console.log(`API server running at ${apiUrl}:${apiPort}`);
});
I installed express and added the line
"api":"node ./src/api.js"
in the package.json file to update the configuration, so now it's defined as
........
........
"private": true,
"scripts": {
"start": "concurrently --kill-others \"npm run app\" \"npm run api\"",
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules",
"api":"node ./src/api.js"
},
"dependencies": {
"#dongido/vue-viaudio": "^0.3.2",
"axios": "^0.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"fs": "0.0.1-security",
"vue": "^2.5.11",
"vue-axios": "^2.1.4",
"vue-router": "^3.0.7"
},
..........
..........
And when I ran the local API server by npm run api, the following was the result when I opened a new tab and directly entered http://localhost:3000/api/feed/get as the URL.
[
{
"avatar": "/avatar/avatar-colshacol.jpg",
"username": "Colton Colcleasure",
"handle": "#colshacol",
"timestamp": 1541851080000,
"content": "",
"media": {
"type": "image",
"url": "/media/media-pony-pooping-rainbow-icecream.gif"
},
"actions": {
"replies": 2,
"rekweets": 41,
"likes": 172
}
},
{
"avatar": "/avatar/dankotaru_ketsui.jpeg",
"username": "ๅฎ‰่ฅฟๅ…ˆ็”Ÿ",
"handle": "#ใƒ›ใƒƒใƒ›ใƒƒใƒ›ใƒƒใƒ›",
"timestamp": 9031851080000,
"content": "ๆœ€ๅพŒใพใงๅธŒๆœ›ใ‚’ๆจใฆใกใ‚ƒใ„ใ‹ใ‚“ใ€‚่ซฆใ‚ใŸใ‚‰ใ€ใใ“ใง่ฉฆๅˆ็ต‚ไบ†ใ ใ‚ˆใ€‚โ€ฆโ€ฆโ€ฆโ€ฆ่žใ“ใˆใ‚“ใฎใ‹๏ผŸใ‚๏ผŸโ€ฆโ€ฆโ€ฆโ€ฆ็งใ ใ‘ใ‹ใญ๏ผŸใพใ ๅ‹ใฆใ‚‹ใจๆ€ใฃใฆใ‚‹ใฎใฏโ€ฆใ€‚",
"actions": {
"replies": 4,
"rekweets": 31,
"likes": 184
}
},
.........
.........
.........
]
as you can see, the JSON file is properly fetched.
But when I enter http://localhost:3000/api/feed/post instead, I only get the response Cannot GET /api/feed/post.
What could be the reason behind this?
And what would be the solution?

SQL Express React Node (SERN Stack) - Best way to handle large Data Payloads?

I work for a company whose clients are other companies. The company recordset in the DB has 40+ fields with ten thousand plus companies (including one field that holds in most cases a ridiculously long string.) The JSON Data payload that comes back via express and a wildcard SQL call is north of 4 million lines in Postman.
Background:
We had this set up using ASMX Web Services in VB.NET but the response to the client was averaging close to thirty seconds when having to serialize the JSON. It was cumbersome and quite a pain to work with.
Going back to the previous version in .NET MVC it would still sometimes take over ten to fifteen seconds to populate a simple select input with the company name much less than render the UI.
The New Environment:
I have currently constructed the system in its 4th generation using a SERN environment with webpack 3+. I have enabled the API to run with CORS on a separate port(5000) from my app's port(8080) and have tested the payload. It is still 8 seconds. Better but not optimal.
The Question:
How can I speed up the payload? I have heard of React being able to split payloads from Node API's but haven't a clue on how to get that done. Can anyone take the code below and either tell me where I can improve or point me to some libraries or something that can speed up the performance of the SQL call or data transfer?
Current POSTMAN Performance stats:
SQL: 2.679 secs
Express: 1.331 secs
API to Client: 3.976 secs
package.json:
{
"name": "project",
"version": "1.0.0",
"description": "desc",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "concurrently \"webpack-dev-server\" \" node ./server/core/server.js\"",
"dev": "webpack-dev-server",
"server": "node ./server/core/server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/djErock/EMR4.git"
},
"author": "Erik Grosskurth",
"license": "MIT",
"bugs": {
"url": "https://github.com/djErock/EMR4/issues"
},
"homepage": "https://github.com/djErock/EMR4#readme",
"dependencies": {
"axios": "^0.16.2",
"cors": "^2.8.4",
"jquery": "^3.2.1",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.1.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-latest": "^6.24.1",
"babel-preset-react": "^6.24.1",
"concurrently": "^3.5.0",
"css-loader": "^0.28.4",
"express": "^4.16.0",
"file-loader": "^0.11.2",
"mssql": "^4.1.0",
"react-hot-loader": "^3.0.0-beta.7",
"style-loader": "^0.18.2",
"webpack": "^3.6.0",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^2.9.1"
}
}
Webpack.config:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
],
},
devServer: {
historyApiFallback: true,
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
]
};
Server.js
const webpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
const config = require('../../webpack.config.js');
const options = {
contentBase: './dist',
hot: true
};
var app = require('express')();
var cors = require('cors');
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
const companies = require("../controllers/company.js");
app.get('/api/companies', function (req, res) {
companies.getCompanyList(req, res);
});
webpackDevServer.addDevServerEntrypoints(config, options);
const compiler = webpack(config);
const server = new webpackDevServer(compiler, options);
app.listen(5000, () => {
console.log('dev server listening on port 5000');
});
comapny.js
var db = require("../core/db");
exports.getCompanyList = function(req, resp) {
db.execSQL("SELECT * FROM tblCompany", function(data, err) {
if (err) {
resp.writeHead(500, "Internal Error Occurred",{"Content-Type": "application/json"});
resp.write(JSON.stringify(err));
}else {
resp.writeHead(200, {"Content-Type": "application/json"});
resp.write(JSON.stringify(data));
}
resp.end();
});
}
DB.js
var sqlDB = require("mssql");
var settings = require("../settings.js");
exports.execSQL = function(sql, callback) {
var conn = new sqlDB.ConnectionPool(settings.dbConfig);
conn.connect().then(function() {
var req = new sqlDB.Request(conn);
req.query(sql).then(function(recordset) {
callback(recordset);
}).catch(function(err) {
console.log(err);
callback(null, err);
});
}).catch(function(err) {
console.log(err);
callback(null, err);
});
};
React with axios ajax call in component:
handleOnChange(e) {
e.preventDefault();
//Let's call the caduceus server
axios.get(Constants.WS_PREFIX+'companies')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
You'd need to have pagination implemented in the api and should use limit-offset in your queries.

npm run script causes Windows Script Host error

I a trying to use npm to minify javascript.
This is my package.json:
{
"name": "name1",
"version": "1.0.0",
"description": "",
"scripts": {
"minifyjs": "minifyJs",
"minifycss": "minifyCss",
"minifyhtml": "minifyHtml"
},
"author": "",
"license": "ISC",
"devDependencies": {
"clean-css": "^3.4.19",
"html-minifier": "^3.0.2",
"uglify-js": "^2.7.0"
}
}
and my minifyJs script is :
var uglifyJS = require('uglify-js');
var fs = require('fs');
var result = uglifyJS.minify(['src/main1.js', 'src/main2.js'], {
compress: {
drop_console: true,
unused: true
}
});
fs.writeFileSync('dist/minifyJs.js', result.code);
When I call npm run minifyjs I get the following error:
What am I doing wrong - btw this was working on another machine.....
Can anyone help?
The entries under scripts are commands that are run by NPM. They are not simply paths to JavaScript files.
You need to tell NPM to run your JavaScript tasks using node:
...
"scripts": {
"minifyjs": "node minifyJs",
"minifycss": "node minifyCss",
"minifyhtml": "node minifyHtml"
},
...