Unexpected <EOF> while using graphql - graphql-js

Getting EOF error every time at same line, changed code many times and even degraded to previous versions of graphql but no positive results.
My code is:
const graphql = require('graphql')
const _ = require('lodash')
const {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLSchema
} = graphql
const users = [
{id: '1', firstName: 'Ansh', age: 20},
{id: '2', firstName: 'Ram', age: 21},
{id: '3', firstName: 'Sham', age: 20}
]
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: {type: GraphQLString},
firstName: {type: GraphQLString},
age: {type: GraphQLInt}
}
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
user: {
type: UserType,
args: {id: {type: GraphQLString}},
resolve(parentValue, args) {
return _.find(users, {id: args.id})
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery
})
Error is:
{
"errors": [
{
"message": "Syntax Error GraphQL request (30:1) Unexpected <EOF>\n\n29: \n30: \n ^\n",
"locations": [
{
"line": 30,
"column": 1
}
]
}
]
}

The issue is because the query you're passing might be empty.
For example:
curl -X POST http://localhost:4000/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ user { id } }"}'
works fine.
But if you make something like:
curl -X POST http://localhost:4000/graphql \
-H "Content-Type: application/json" \
-d '{"query": ""}'
You'll get unexpected < EOF >
Also, check GraphQL end of line issue.

I had comments in the schema.graphql file:
"""
Some comments
"""
I removed the comments and the Unexpected <EOF> error went away.

It's because there's no actual query so you get unexpected EOF (End of File).
Guessing that you're using GraphiQL (because your EOF message says line 30); you need to add a query on the left-hand panel of GraphiQL in the browser. Something which conforms to your RootQuery like:
{
user(id: "1") {
id,
firstName,
age
}
}

I got this error while trying to stitch my schema
the reason for this error was that I delcared a type but didn't implemet it, had empty body, for example:
type User {
}
implementing the type fixed it

It looks like if we are doing the schema-first approach, but we do not have any .graphql files in your project/empty. I added this and the error went away:
src/example.graphql
type Query {
hello: String
}
The "GraphQLError: Syntax Error: Unexpected " error is coming from the graphql package. It looks like #nestjs/graphql is assuming that there will always be at least one .graphql file, so this is probably a bug to try and parse an empty schema vs display a more developer-friendly message or ignore it.

In most cases passing an empty query is caused to this error.
To avoid this try this in your graphiql
query {
user {
fields you need to retrieve
}
}

This is because your graphql.gql looks like this:
# ------------------------------------------------------
# THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)
# ------------------------------------------------------
directive #key(fields: String!) on OBJECT | INTERFACE
directive #extends on OBJECT | INTERFACE
directive #external on OBJECT | FIELD_DEFINITION
directive #requires(fields: String!) on FIELD_DEFINITION
directive #provides(fields: String!) on FIELD_DEFINITION
One thing you can do is create a dummy resolver.
// src/graphql/resolvers/user.resolver.ts
import { Resolver, Query } from '#nestjs/graphql';
import { User } from 'models/User.model';
#Resolver(() => User)
export class UserResolver {
#Query(() => User)
async ids() {
return [];
}
}
and create a graphql model:
// src/graphql/models
import { Field, ObjectType } from '#nestjs/graphql';
#ObjectType()
export class User {
#Field()
createdAt: Date;
}
And make sure that resolver is imported by a module and the module is added to App.module
This should fix it!

In my case on the frontend side (Angular), since I just wanted to observe something, I have this code:
I got this error:
Error: Unexpected <EOF>.
and I made it comment-line and the error was gone

How to fix it: Go to node_mudules > graphql > syntaxError.js and delete all comments from this file and the error should be gone.

Related

Mongo Bulkwrite with $addToSet

I have been trying a bulkwrite but get complained about typing (I think it's about the syntax):
Type '{ roles: string; }' is not assignable to type 'SetFields<any>'.
Type '{ roles: string; }' is not assignable to type 'NotAcceptedFields<any, readonly any[]>'.
Property 'roles' is incompatible with index signature.
Type 'string' is not assignable to type 'never'.ts(2345)
I can't find any examples or docs about using $addToSet in a builkwrite. Here it is (INTER_ADMINS is just an array of string):
const bulkUpdates = INTER_ADMINS.map((ethAddress) => {
return {
updateOne: {
filter: { ethAddress },
update: {
$addToSet: {
roles: 'INTERNAL_ADMIN',
},
},
upsert: true,
},
};
});
const res = await db.collection('users').bulkWrite(bulkUpdates);
users collection sample:
{
ethAddress: 'something',
roles: ['role1','role2']
}
Appreciate your help
The syntax is correct, this is just a typescript error. I recommend you just add a #ts-ignore and move on.
Here is the type definition:
export type UpdateQuery<TSchema> = {
....
$addToSet?: SetFields<TSchema> | undefined;
....
};
export type SetFields<TSchema> = ({
readonly [key in KeysOfAType<TSchema, ReadonlyArray<any> | undefined>]?:
| UpdateOptionalId<Unpacked<TSchema[key]>>
| AddToSetOperators<Array<UpdateOptionalId<Unpacked<TSchema[key]>>>>;
} &
NotAcceptedFields<TSchema, ReadonlyArray<any> | undefined>) & {
readonly [key: string]: AddToSetOperators<any> | any;
};
As you can see because the Schema is not provided typescript doesn't know which are the valid "keys" of the schema so the only valid type left in the SetFields is the NotAcceptedFields fields type (which are null and undefined, not string )
If you provide a Schema to the operations I believe it should sort the issue:
const bulkUpdates: BulkWriteOperation<UserSchema>[] = ...

graphql-tools, how can I use mockServer to mock a "Mutation"?

I try to use mockServer of graphql-tools to mock an Mutation.
here is my unit test:
it('should update user name correctly', () => {
mockserver
.query(
`{
Mutation {
updateUserName(id: 1, name: "du") {
id
name
}
}
}`
)
.then(res => {
console.log(res);
expect(1).to.be.equal(1);
});
});
But, got an error:
mock server test suites
✓ should get users correctly
✓ should get user by id correctly
✓ should update user name correctly
{ errors:
[ { GraphQLError: Cannot query field "Mutation" on type "Query".
at Object.Field (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/validation/rules/FieldsOnCorrectType.js:65:31)
at Object.enter (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/language/visitor.js:324:29)
at Object.enter (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/language/visitor.js:366:25)
at visit (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/language/visitor.js:254:26)
at visitUsingRules (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/validation/validate.js:74:22)
at validate (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/validation/validate.js:59:10)
at graphqlImpl (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/graphql.js:106:50)
at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/graphql.js:66:223
at new Promise (<anonymous>)
at Object.graphql (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql/graphql.js:63:10)
at Object.query (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/graphql-tools/dist/mock.js:19:63)
at Context.it (/Users/ldu020/workspace/apollo-server-express-starter/src/mockServer/index.spec.js:95:8)
at callFn (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runnable.js:383:21)
at Test.Runnable.run (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runnable.js:375:7)
at Runner.runTest (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:446:10)
at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:564:12
at next (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:360:14)
at /Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:370:7
at next (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:294:14)
at Immediate.<anonymous> (/Users/ldu020/workspace/apollo-server-express-starter/node_modules/mocha/lib/runner.js:338:5)
at runCallback (timers.js:763:18)
at tryOnImmediate (timers.js:734:5)
at processImmediate (timers.js:716:5)
message: 'Cannot query field "Mutation" on type "Query".',
locations: [Array],
path: undefined } ] }
and, I read graphql-tools interface.d.ts file.
export interface IMockServer {
query: (query: string, vars?: {
[key: string]: any;
}) => Promise<ExecutionResult>;
}
Obviously, there is no mutation function in mockServer.
Does mockServer support Mutation?
https://github.com/apollographql/graphql-tools/issues/279
It's the structure of your query. The query should be structured much like you would in GraphiQL such as:
mutation {
updateUserName(id: 1, name: "du") {
id
name
}
}
Hence, your code should look something like this, with the mutation keyword as the first thing in your query before your opening brace { :
it('should update user name correctly', () => {
mockserver
.query(`mutation {
updateUserName(id: 1, name: "du") {
id
name
}
}`)
.then(res => {
console.log(res);
expect(1).to.be.equal(1);
});
});

OrientJS: How to get standard JSON (serialized) from query

I don't understand how to get standard JSON back from an orientjs query. I see people talking about "serializing" the result, but I don't understand why or how to do that. There is a toJSON() method, but i only see it being used with fetchplans etc...
I am trying to pipe a stream to a csv file and it isn't working properly because of the incorrect JSON format.
I would love an explanation of how and when to serialize. :-)
My Query:
return db.query(
`SELECT
id,
name,
out('posted_to').name as page,
out('posted_to').id as page_id,
out('posted_to').out('is_language').name as language,
out('posted_to').out('is_network').name as network
FROM post
WHERE posted_at
BETWEEN
'${since}'
AND
'${until}'
UNWIND
page,
page_id,
language,
network
`
My Result:
[ { '#type': 'd',
id: '207109605968597_1053732754639607',
name: '10 maneiras pelas quais você está ferindo seus relacionamentos',
page: 'Eu Amo o Meu Irmão',
page_id: '207109605968597',
language: 'portuguese',
network: 'facebook',
'#rid': { [String: '#-2:1'] cluster: -2, position: 1 },
'#version': 0 },
{ '#type': 'd',
id: '268487636604575_822548567865143',
name: '10 maneiras pelas quais você está ferindo seus relacionamentos',
page: 'Amo meus Filhos',
page_id: '268487636604575',
language: 'portuguese',
network: 'facebook',
'#rid': { [String: '#-2:3'] cluster: -2, position: 3 },
'#version': 0 }]
This is my dataset:
Query:
db.select('id','code').from('tablename').where({deleted:true}).all()
.then(function (vertex) {
console.log('Vertexes found: ');
console.log(vertex);
});
Output:
Vertexes found:
[ { '#type': 'd',
id: '6256650b-f5f2-4b55-ab79-489e8069b474',
code: '4b7d99fa-16ed-4fdb-9baf-b33771c37cf4',
'#rid': { [String: '#-2:0'] cluster: -2, position: 0 },
'#version': 0 },
{ '#type': 'd',
id: '2751c2a0-6b95-44c8-966a-4af7e240752b',
code: '50356d95-7fe7-41b6-b7d9-53abb8ad3e6d',
'#rid': { [String: '#-2:1'] cluster: -2, position: 1 },
'#version': 0 } ]
If I add the instruction JSON.stringify():
Query:
db.select('id','code').from('tablename').where({deleted:true}).all()
.then(function (vertex) {
console.log('Vertexes found: ');
console.log(JSON.stringify(vertex));
});
Output:
Vertexes found:
[{"#type":"d","id":"6256650b-f5f2-4b55-ab79-489e8069b474","code":"4b7d99fa-16ed-
4fdb-9baf-b33771c37cf4","#rid":"#-2:0","#version":0},{"#type":"d","id":"2751c2a0
-6b95-44c8-966a-4af7e240752b","code":"50356d95-7fe7-41b6-b7d9-53abb8ad3e6d","#ri
d":"#-2:1","#version":0}]
Hope it helps
I found a way that worked for me. instead of using :
db.query()
i used http request in node to query on database. on OrientDB Document also said you get only JSON format in result. this way if you query in database you will always get a valid JSON.
for making a http request i used request module.
this is a sample that worked for me :
var request = require("request");
var auth = "Basic " + new Buffer("root" + ":" + "root").toString("base64")
request(
{
url : encodeURI('http://localhost:2480/query/tech_graph/sql/'+queryInput+'/20'),
headers : {
"Authorization" : auth
}
},
function (error, response, body) {
console.log(body);
return body;
}
);

Sails.js controller not inserting into Mongo database

I've been all over SO and Sailsjs.org trying to figure out what's going wrong, and to no avail. Just trying to learn the basics of SailsJS. I have a UserController, whose create() method gets called when a POST request is sent to /user.
create: function (req, res) {
var params = req.params.all();
User.create({
name: params.FirstName + ' ' + params.LastName,
email: params.Email,
password: params.Password,
jobTitle: params.JobTitle
}).exec(function createCB(err,created)
{
created.save(function(err)
{
// No error . . . still nothing in db
});
return res.json({name: created.name, jobTitle: created.jobTitle, email: created.email, password: created.password});
});
}
No errors here. All the request params are coming in fine and going back to the client without trouble. But nothing is actually being written to the database.
In development.js:
connections: {
mongo: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
// user: 'username',
// password: 'password',
database: 'sails_test'
}
},
models: {
connection: 'mongo'
}
I've tried this with the above both there in development.js, as well as separately in connections.js and models.js, respectively. No difference.
In User.js:
attributes: {
FirstName : { type: 'string' },
LastName : { type: 'string' },
Email : { type: 'string' },
Password : { type: 'string' },
JobTitle : { type: 'string' }
}
My front end request:
$.ajax({
method: 'post',
url: '/user',
data: {
FirstName: 'Yo',
LastName: 'Momma',
Email: 'yourmom#yourdadshouse.com',
Password: 'YouWish123',
JobTitle: 'Home Maker Extraordinaire'
},
success: function (sailsResponse)
{
$('#result').html(sailsResponse).fadeIn();
},
error: function()
{
console.log('error');
}
});
Again, none of this is producing an explicit error. There is just nothing being inserted into the database. Or if there is, I don't know how to find it. I've confirmed the existence of this db in the mongo shell, thusly:
show dbs
My db, sails_test shows up in the list. And I've confirmed that there isn't anything in it like so:
db.sails_test.find()
I would very much appreciate some guidance here :)
Update:
Turns out the data is being written just fine. I'm just unable to query the database from the command line. I confirmed this by first creating a sample user, and then using Waterline's findOne() method:
User.findOne({FirstName: params.FirstName}).exec(function (err, user) {
if (err) {
res.send(400);
} else if (user) {
return res.json({firstName: user.FirstName, lastName: user.LastName, jobTitle: user.JobTitle, email: user.Email, password: user.Password});
} else {
return res.send('no users match those criteria');
}
});
The above works as expected. So my problem now is simply that I cannot interact with the database from the command line. db.<collectionName>.find({}) produces nothing.
This was simply a failure to understand the MongoDb docs. I read db.collection.find({}) as DatabaseName.CollectionName.find({}), when you literally need to use db. So if my database is Test, and my collection is Users, the query is use Test, and then db.Users.find({}).
Also of note, 3T Mongo Chef is a pretty rockin' GUI (graphical user interface) for nosql databases, and it's free for non-commercial use.

Cannot save a document in Mongoose - Validator required failed for path error

Following is my schema:
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: false
}
});
Now, when I attempt to save a document of the above schema, I get the following error:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' } } }
The above is the error object returned by mongoose upon save. I searched for this error but could not understand what is wrong. The document that I am trying to save is as follows:
{
username: "foo"
password: "bar"
}
Any idea what this means? I searched the mongoose docs too but could not find anything under the validation section.
First, you are missing a comma (,) after foo.
Now, is { username: "foo", password: "bar" } JSON sent via http, our an actual object in your server-side code ?
If it is, try to console.log(youVariable.username) and see if it shows undefined or the value foo. If you see undefined, then your object is not parsed properly.
You can make sure that whom ever is sending the POST request is sending a "application/json" in the header, you could be receiving something else, thus your JSON isn't parsed to a valid javascript object.