I am trying to get a reference implementation of GraphQL.js working in a Node.js environment as a server. Note that I have limited experience with Node.js. Right now, I am using node v4.2.6, which is the latest package from Ubuntu for Ubuntu 16.04.
The official documentation says that this script should work:
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
That fails with a syntax error:
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
The express-graphql project site shows a significantly different script, but one where I have to assemble a schema separately. The GraphQL.js project site has this script for assembling a schema:
import {
graphql,
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from 'graphql';
var schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQueryType',
fields: {
hello: {
type: GraphQLString,
resolve() {
return 'world';
}
}
}
})
});
That too fails with a syntax error:
server.js:1
(function (exports, require, module, __filename, __dirname) { import {
^^^^^^
SyntaxError: Unexpected reserved word
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
I am guessing that perhaps v4.2.6 of Node.js is too old. Is that correct? If so, what is the minimum version of Node.js required to use GraphQL.js and express-graphql? And, if that's not my problem... any idea what is?
tThe prerequisites for that tutorial say:
Before getting started, you should have Node v6 installed [...]
Though to be fair it continues with:
[...] , although the examples should mostly work in previous versions of Node as well.
Node v4 doesn't support destructuring, which is the part it's choking on for you. You can check out node.green for a reference on what features are supported by what Node versions.
That too fails with a syntax error:
import|export aren't supported in any version of Node. You'd have to transpile that. Or you can just use Node's module system. For that it should look something like:
var graphqlModule = require("graphql");
var graphql = graphqlModule.graphql;
var GraphQLSchema = graphqlModule.GraphQLSchema;
// ...
Related
I am getting a syntax error on trying to set up swagger with typescript express app. When I tried this without the swagger-jsdoc i.e using swagger.json it was working but when I am trying to use swagger-jsdoc for documenting I am facing the following error
So please can any body help me in resolving this issue.
This is my app.ts
import bodyParser from "body-parser";
import express, { RequestHandler } from "express";
import morgan from "morgan";
import v1 from "./routes/v1";
import swaggerUi from "swagger-ui-express";
import swaggerJsdoc from "swagger-jsdoc";
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const swaggerDefinition = {
openapi: "3.0.0",
info: {
title: "Homework APP",
version: "0.1.0",
description: "This is a simple CRUD API application made with Express and documented with Swagger",
},
servers: [
{
"url": "/",
"description": "Local Dev"
},
],
}
const options = {
swaggerDefinition,
apis: ["./src/routes/v1/*.ts"],
}
const specs = swaggerJsdoc(options);
app.use(morgan(":status :method :url :response-time ms"));
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs))
app.use(v1);
export default app;
ERROR
(function (exports, require, module, __filename, __dirname) { import { prepare, extract, organize, finalize } from './src/specification.js';
^
SyntaxError: Unexpected token {
at new Script (vm.js:79:7)
at createScript (vm.js:251:10)
at Object.runInThisContext (vm.js:303:10)
at Module._compile (internal/modules/cjs/loader.js:656:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Module.load (internal/modules/cjs/loader.js:598:32)
at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
at Function.Module._load (internal/modules/cjs/loader.js:529:3)
at Module.require (internal/modules/cjs/loader.js:636:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/home/aman/Documents/Octo/homeworkapp-server/src/app.ts:6:1)
at Module._compile (internal/modules/cjs/loader.js:688:30)
at Module.m._compile (/home/aman/Documents/Octo/homeworkapp-server/node_modules/ts-node/src/index.ts:1056:23)
at Module._extensions..js (internal/modules/cjs/loader.js:699:10)
at Object.require.extensions.(anonymous function) [as .ts] (/home/aman/Documents/Octo/homeworkapp-server/node_modules/ts-node/src/index.ts:1059:12)
at Module.load (internal/modules/cjs/loader.js:598:32)
[nodemon] app crashed - waiting for file changes before starting...
I was able to resolve this issue by rolling back the swagger-jsdoc version to "swagger-jsdoc": "^6.0.0"
An anonymous error in my 'logs' section came on firebase project, while no error was shown on 'run' in Android studio. I don't know anything about node js, i just wanted to link my app through it, that's why i am forced to use it, can someone help me please.
Here's the complete error on firebase project -> Functions -> logs
srv/node_modules/#google-cloud/firestore/build/src/collection-group.js:54
async *getPartitions(desiredPartitionCount) {
^
SyntaxError: Unexpected token *
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/node_modules/#google-cloud/firestore/build/src/index.js:39:28)
Here's the second error on firebase's project -> functions -> logs. :
Error detected in onCreateFollower {"errorEvent":{"eventTime":"2020-10-31T06:41:42.682Z","message":"/srv/node_modules/#google-cloud/firestore/build/src/collection-group.js:54\n async *getPartitions(desiredPartitionCount) {\n ^\n\nSyntaxError: Unexpected token *\n at createScript (vm.js:80:10)\n at Object.runInThisContext (vm.js:139:10)\n at Module._compile (module.js:617:28)\n at Object.Module._extensions..js (module.js:664:10)\n at Module.load (module.js:566:32)\n at tryModuleLoad (module.js:506:12)\n at Function.Module._load (module.js:498:3)\n at Module.require (module.js:597:17)\n at require (internal/module.js:11:18)\n at Object.<anonymous> (/srv/node_modules/#google-cloud/firestore/build/src/index.js:39:28)","serviceContext":{"service":"onCreateFollower","resourceType":"cloud_function"}},"#type":"type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.Insight","errorGroup":"COvaxM_ErLfhbg"
Here's the code in Android Studio on index.js file -
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// functions.logger.info("Hello logs!", {structuredData: true});
// response.send("Hello from Firebase!");
// });
exports.onCreateFollower = functions.firestore.document("/followers/{userId}/userFollowers/{followerId}").onCreate(async (snapshot, context) => {
console.log('Follower Created', snapshot.id);
const userId = context.params.userId;
const followerId = context.params.followerId;
const followedUserPostsRef = admin.firestore().collection('posts').doc(userId).collection('userPosts');
const timelinePostsRef = admin.firestore().collection('timeline').doc(followerId).collection('timelinePosts');
const querySnapshot = await followedUserPostsRef.get();
querySnapshot.forEach(doc => {
if(doc.exists) {
const postId = doc.id;
const postData = doc.data();
timelinePostsRef.doc(postId).set(postData);
}
})
});
try this "firebase-admin": "^8.13.0","firebase-functions": "^3.6.1". This solved my problem.
Change the version of firebase-admin to "firebase-admin": "^ 8.10.0" and firebase-functions to "firebase-functions": "^ 3.6.1". I also had this problem and solved it.
I got this error in my application that is previously working
const usersCollection = require('../db').db().collection("users")
^
TypeError: require(...).db is not a function
at Object.<anonymous> (/Users/user/Desktop/sites/app/models/User.js:2:42)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/user/Desktop/sites/app/controllers/userController.js:1:14)
db.js
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology:
true}, function(err, client) {
module.exports = client
const app = require('./app')
app.listen(process.env.PORT)
})
.env file
CONNECTIONSTRING=mongodb+srv://user:password#sandbox-gk8wp.mongodb.net/db?
retryWrites=true&w=majority
PORT=3000
I have updated also my mongodb npm package from 3.3.3 to 3.4.1 but still the same error. What seems to be the problem?
You are trying to export something in the callback which may or may not be available when you import it as it is asynchronous method. Better way will be to create db.js like
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
function getMongoClient() {
return mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology: true});
}
module.exports = getMongoClient;
And when you want to use it
const getMongoClient = require('../db');
getMongoClient()
.then(client => client.db().collection("users"));
Hope this helps. You could also use async/await.
Within my Azure App Service Node.js backend I cannot seem to get the Javascript async/await feature to run. I have changed the default version of Node.js within application settings and package.json to above 7.6. (Changed to 8.9.0)
I would like to use this feature within a custom Express router shown here:
var express = require('express'),
bodyParser = require('body-parser');
var router = express.Router();
router.get('/', function (req, res, next) {
res.status(200).send('GET: This is a test response!');
});
router.post('/:id', async function (req, res, next) {
var context = req.azureMobile;
var newLovedOne = req.body.lovedone;
var newTie = req.body.tie;
console.log('POST: newLovedOne ', newLovedOne);
console.log('POST: newTie ', newTie);
try {
await context.tables('Tie').insert(newTie);
await context.tables('LovedOne').insert(newLovedOne);
} catch (error) {
res.status(500).send('Insert failed!');
}
});
module.exports = router;
Attempting to start the app with the above router produces this:
Application has thrown an uncaught exception and is terminated:
SyntaxError: missing ) after argument list
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (D:\home\site\wwwroot\app.js:12:20)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
To verify whether the Node.js version is correctly set, you can go to your root and open the iisnode.yml file. Make sure it has the following line with the correct version:
nodeProcessCommandLine: "D:\Program Files (x86)\nodejs\8.9.0\node.exe"
am trying to integrate coinpayments into my site am using express js to run it i have gone through the npm docs but it still seems unclear to me and i have tried running some code and still nothing shows up. Any help is highly appreciated.
var express = require("express"),
app = express(),
coinpayments = require("coinpayments"),
bodyparser = require("body-parser")
app.use(bodyParser.urlencoded({extended: true}));
var Coinpayments = require('coinpayments');
var client = new Coinpayments({
key: kfjdkjfkdfkf00d00,
secret: 009093403440349,
});
client.getBasicInfo(function(error,result){
if(error){
console.log(error)
} else{
console.log(result)
}
})
it throws up error in my command line
sniperfillipo:~/workspace/bitcointest/main $ node crypto.js
/home/ubuntu/workspace/bitcointest/main/node_modules/coinpayments/lib/index.js:28
throw new Error('Missing public key and/or secret');
^
Error: Missing public key and/or secret
at new CoinPayments (/home/ubuntu/workspace/bitcointest/main/node_modules/coinpayments/lib/index.js:28:19)
at Object.<anonymous> (/home/ubuntu/workspace/bitcointest/main/crypto.js:235:14)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:504:3
Am new to this don't really know for sure how things work
The issue is this section here:
var client = new Coinpayments({
key: kfjdkjfkdfkf00d00, // <-- this line
secret: 009093403440349,
});
What is kfjdkjfkdfkf00d00? It is neither aString nor a Number. It is an undeclared variable.
So you are passing an undeclared variable into the constructor of Coinpayments which takes on the value of undefined judging from the error message you provided.
So your actual constructor looks like:
var client = new Coinpayments({
key: undefined,
secret: 009093403440349,
});
In other words, you need to define your key value.