unexpected token while runing gaphql server - graphql-js

i runing my graphql server via terminal,, but when i am runing
$node server
geeting error like this
/home/bimoan/Desktop/bibitnomic-api/server.js:3
var { buildSchema } = require("graphql");
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
this is my server.js
var express = require("express");
var express_graphql = require("express-graphql");
var { buildSchema } = require("graphql");
// GraphQL schema
var schema = buildSchema(`
type Query {
message: String,
User: String
}
`);
// Root resolver
var root = {
message: () => "Hello World!",
User: () => " Bimo ANugrah"
};
// Create an express server and a GraphQL endpoint
var app = express();
app.use(
"/graphql",
express_graphql({
schema: schema,
rootValue: root,
graphiql: true
})
);
app.listen(4000, () =>
console.log("Express GraphQL Server Now Running On localhost:4000/graphql")
);
where my code is wrong ??
I was not change anything what and why this can happen? Can anyone help me?

Related

I am getting error that say -> TypeError: Class constructor MongoStore cannot be invoked without 'new'

`Error TypeError: Class constructor MongoStore cannot be invoked without 'new'
** MY code is:**
const url = 'mongodb://localhost/pizza';
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
const connection = mongoose.connection;
mongoose.connection
.once('open', function () {
console.log('Database connected');
})
.on('error', function (err) {
console.log(err);
});
// session
let mongoStore = new MongoDbStore({
mongooseConnection: connection,
collection: 'sessions'
})```
```// session config
app.use(session({
secret: process.env.COOKIE_SECRET,
resave: false,
store: mongoStore,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 } // 24 hour
}))```
`
**This is the error i am getting **`
const MongoDbStore = require('connect-mongo')(session)
^
TypeError: Class constructor MongoStore cannot be invoked without 'new'
at Object. (C:\Projects\pizza\server.js:21:46)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
`Please help to solving the error `
`**I tried some solution from thee stackOverflow but still not able to solve the problem**`

I have some problem with my homework to connect to mongodb using mongoose

const mongoose = require("mongoose")
const app = require("../app")
const dotenv = require("dotenv");
dotenv.config();
const PORT = process.env.PORT || 3000
const DB_PATH = process.env.DB_CONNECTION_URL
const db = mongoose
.connect(DB_PATH, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log("Database connection successful");
app.listen(PORT, () => {
console.log(`Server running. Use our API on port: ${PORT}`);
});
})
.catch((error) => {
console.log(error);
process.exit(1);
});
module.exports = db
Snapshot
MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
at NativeConnection.Connection.openUri (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/connection.js:694:11)
at /Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:351:10
at /Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:1149:10)
at Mongoose.connect (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/node_modules/mongoose/lib/index.js:350:20)
at Object. (/Volumes/Mac - Data/GitHub/hw7/nodejs-homework2-rest-api/bin/server.js:11:4)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

Error: Cannot init client | mongo-connect express-session

I am getting error while trying to save session on mongodb. Here is my code..
const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo").default;
const app = express();
let sessionOptions = session({
secret: "JavaScript is cool",
store: MongoStore.create({ client: require("./db") }),
resave: false,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});
app.use(sessionOptions);
const router = require("./router");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));
app.set("views", "views");
app.set("view engine", "ejs");
app.use("/", router);
module.exports = app;
and db.js
const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");
mongodb.connect(
process.env.CONNECTIONSTRING,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
module.exports = client;
const app = require("./app");
app.listen(process.env.PORT);
}
);
And the error is here..
Assertion failed: You must provide either mongoUr|clientPromise in options
/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121
throw new Error('Cannot init client');
^
Error: Cannot init client
at new MongoStore (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121:19)
at Function.create (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:137:16)
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:9:21)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
I tried to change from const MongoStore = require("connect-mongo").default to const MongoStore = require("connect-mongo")(session)
But the error is showing..
const MongoStore = require("connect-mongo")(session);
^
TypeError: require(...) is not a function
at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:4:44)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at mongodb.connect (/home/irfan/Desktop/Brad_Sciff/Complex_App/db.js:10:17)
at /home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/mongodb/lib/utils.js:693:5
Using Connect-mongo 4.2, express-session 1.17.1 express 4.17.1 mongodb 3.6.4
Don't know what I am missing.
Please help.
Thanks in Advance.
Irfan.
So it looks like connect-mongo has been updated recently. I came across this issue today as well and here's how I fixed it.
How it used to be:
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
app.use(
session({
...options
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
How it is now:
const session = require('express-session');
const MongoStore = require('connect-mongo').default;
app.use(
session({
store: MongoStore.create({ mongoUrl: process.env.MONGO_URI }),
...options
})
);
Try passing your connection string into mongoURL instead of client and see if that helps.
You can read more about connect-mongo in their docs.
the following is worked for me.
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const url = 'mongodb://localhost/mydb';
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true,
useUnifiedTopology: true, useFindAndModify: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("database connected successfully...");
}).catch(err => {
console.log("connection failed...");
});
// session store
let store = new MongoStore({
mongoUrl: url,
collection: "sessions"
});
// session config
app.use(session({
secret: process.env.COOKIE_SECRET,
resave: false,
store: store,
saveUninitialized: false,
cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 24 hours
}));
what I did was to downgrade from mongodb version 4 to version 3. Hence, in your terminal, uninstall connect-mongo and reinstall lower version.
"npm uninstall connect-mongo"
"npm i connect-mongo#3"
this allows you to be able to pass in your session to the MongoStore.
"const path = require('path')
const express = require('express')
const mongoose = require ('mongoose')
const dotenv = require('dotenv')
const morgan = require('morgan')
const exphbs = require ('express-handlebars')
const passport = require('passport')
const session = require ('express-session')
const MongoStore = require('connect-mongo')(session)"
This is latest solution
add this lines
First
var session = require('express-session');
var MongoStore = require ('connect-mongo');
Second
app.use(session(
{
secret: '**something** like mysupersecret',
store: MongoStore.create({
mongoUrl: '**your url**like mongodb://localhost/test-app'}),
}));
There is an another npm package connect-mongodb-session,
https://www.npmjs.com/package/connect-mongodb-session
Install it and it should work.
const MongoDBStore = require('connect-mongodb-session')(session);
This worked for me,
const session = require('express-session');
const MongoStore = require('connect-mongo');
const dbUrl = process.env.DB_URL;
app.use(session({
secret: 'thisismysecret',
resave: false,
saveUninitialized: false,
store: MongoStore.create( {
mongoUrl: dbUrl,
touchAfter: 24 * 3600
}) }));

Now Mongoose Cannot overwrite model once compiled

I'm using MongoDB Atlas to host the DB and just querying data with this severless function:
import { NextApiRequest, NextApiResponse } from "next";
// models
import { Section } from "../../../models/Section";
// db connection
import { useDatabase } from "../../../middleware/useDatabase";
async function find(req: NextApiRequest, res: NextApiResponse) {
const { content } = req.query;
const response = await Section.find({ contentType: content });
res.send(response);
}
export default useDatabase(find);
The middleware useDatabase is configured like this:
import * as mongoose from "mongoose";
import { NextApiRequest, NextApiResponse } from "next";
export const useDatabase = handler => async (req: NextApiRequest, res: NextApiResponse) => {
if (mongoose.connections[0].readyState) return handler(req, res);
// Using new database connection
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
});
return handler(req, res);
}
The first time I execute the query doing a fetch to the api, works well, then if I edit some code, save it and now dev recompile the code, I got this error when I do the query again:
MongooseError [OverwriteModelError]: Cannot overwrite `Section` model once compiled.
at new OverwriteModelError (/home/andres/Documents/shooter-app/node_modules/mongoose/lib/error/overwriteModel.js:20:11)
at Mongoose.model (/home/andres/Documents/shooter-app/node_modules/mongoose/lib/index.js:521:13)
at Module../models/Section.ts (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:154:63)
at __webpack_require__ (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:23:31)
at Module../pages/api/sections/[content].ts (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:198:73)
at __webpack_require__ (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:23:31)
at Object.3 (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:233:18)
at __webpack_require__ (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:23:31)
at /home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:91:18
at Object.<anonymous> (/home/andres/Documents/shooter-app/.next/server/static/development/pages/api/sections/[content].js:94:10)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at DevServer.handleApiRequest (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:420:28)
at async Object.fn (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:350:37)
at async Router.execute (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/router.js:42:32)
at async DevServer.run (/home/andres/Documents/shooter-app/node_modules/next/dist/next-server/server/next-server.js:468:29) {
message: 'Cannot overwrite `Section` model once compiled.',
name: 'OverwriteModelError'
}
How can I solve it? Thank you!
This happens when the development server tries to recompile your model during hot module replacement.
You can prevent this from happening by changing your code to check whether the model has already been compiled when exporting it.
export default mongoose.models['Section'] || mongoose.model('Section', SectionSchema);

graphql-compose-mongoose generating an error: Expected [object Object] to be a GraphQL schema

I'm new to graphql-compose
I'm trying to launch a first service on a simple mongoose schema:
graphql.js :
import mongoose from 'mongoose'
import { composeWithMongoose} from 'graphql-compose-mongoose'
import { schemaComposer } from 'graphql-compose'
const db = require( '../models/db' )
//const mongoose = require('mongoose');
const folderDAO = mongoose.model('folder');
const customizationOptions = {}; // left it empty for simplicity, described below
const folderTC = composeWithMongoose(folderDAO, customizationOptions);
schemaComposer.rootQuery().addFields({
folderOne: folderTC.getResolver('findOne'),
})
const graphqlSchema = schemaComposer.buildSchema()
console.log("Schema built : ", graphqlSchema )
export default graphqlSchema
Now in my server code, I have this:
const express = require('express');
const graphqlHTTP = require('express-graphql')
const GraphQLSchema = require('./app_api/routes/graphql')
app.use('/graphql', graphqlHTTP({
schema: GraphQLSchema,
graphiql: true,
formatError: error => ({
message: error.message,
locations: error.locations,
stack: error.stack ? error.stack.split('\n') : [],
path: error.path
})
}));
On graphiql, when I attempt the following query:
{
folderOne(filter: {}, sort: _ID_ASC) {
name
}
}
I get the following error:
{
"errors": [
{
"message": "Expected [object Object] to be a GraphQL schema.",
"stack": [
"Error: Expected [object Object] to be a GraphQL schema.",
" at invariant (/Users/zied/work/share_place/node_modules/graphql/jsutils/invariant.js:19:11)",
" at validateSchema (/Users/zied/work/share_place/node_modules/graphql/type/validate.js:55:60)",
" at assertValidSchema (/Users/zied/work/share_place/node_modules/graphql/type/validate.js:80:16)",
" at validate (/Users/zied/work/share_place/node_modules/graphql/validation/validate.js:58:35)",
" at /Users/zied/work/share_place/node_modules/express-graphql/dist/index.js:139:52",
" at <anonymous>",
" at process._tickDomainCallback (internal/process/next_tick.js:228:7)"
]
}
]
}
What could I be missing???
p.s: sorry I attempted to tag the question with graphql-compose-mongoose but the tag doesn't exist, so I tagged it with graphql-js
Actually the issue was here:
const GraphQLSchema = require('./app_api/routes/graphql')
has to be replaced with
const GraphQLSchema = require('./app_api/routes/graphql').default
since we exported it as default
More info can be found here: https://github.com/graphql-compose/graphql-compose-mongoose/issues/103