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>[] = ...
Related
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.
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);
});
});
I want to change my Rest-API validation to node simple schema for schema definition and collection2#core for schema validation.
I want to use the Person schema to validate the data provided by the users.
Schemas = {};
Schemas.Person = new SimpleSchema({
name: {
type: String,
label: "Person's Name",
unique: true,
max: 200
},
surname: {
type: String,
unique: true,
label: "person's surname"
},
};
validData = API.utility.validate(data, Schemas.Person });
API: {
utility: {
validate: function(data, schema) {
return "The SimpleSchema Validation";
}
}
};
This case is described in the simpl-schema documentation
With your schema definition you can just do:
Schemas.person.validate(data);
If right after that you want to look at the result or the errors:
Schemas.person.isValid();
Schemas.person.validationErrors();
Suppose I have a PG ARRAY field:
id | array |
===|=============|
1|{"1","2","3"}|
How do I use sequelize to query to see if the array field as the value 1.
I tried:
array: { $contains: "1" }
which gives me:
array #> "1"
with error:
Possibly unhandled SequelizeDatabaseError: array value must start with "{" or dimension information
UPDATE
I was able to do it by:
array: { $contains: '{' + value + '}' }
Is there a more correct way?
I realised that sequelize is expecting the condition to be an array:
array: { [Op.contains]: ["1"] }
That will work. Cheers!!
Bear in mind that Op is exported from sequelize
const { Op } = require('sequelize');
or
import { Op } from 'sequelize';
See official docs: https://sequelize.org/master/manual/model-querying-basics.html#operators
Maybe so.
`{ genres: { $contains: [genreType] } }`
genres is an array. genreType can also be an array.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
operatorsAliases: Sequelize.Op.Aliases,
});
I have the following in my Sailsjs config/adapter.js:
module.exports.adapters = {
'default': 'postgres',
postgres : {
module : 'sails-postgresql',
host : 'xxx.compute-1.amazonaws.com',
port : 5432,
user : 'xxx',
password : 'xxx',
database : 'xxx',
ssl : true,
schema : true
}
};
And in models/Movie.js:
Movie = {
attributes: {
tableName: 'movies.movies',
title: 'string',
link: 'string'
}
};
module.exports = Movie;
In my controller:
Movie.query("SELECT * FROM movies.movies", function(err, movies) {
console.log('movies', movies.rows);
});
movies.rows DOES return the correct data
However:
Movie.find({ title: 'Frozen' }, function(err, movies) {
console.log('movies', movies)
});
movies returns an EMPTY ARRAY
So it seems all connections are good because the raw query works perfectly.
Could there be something I am doing wrong with setting up the Movie.find() or with models/Movie.js?
Does the tableName attribute not support postgresql schema_name.table_name?
First off, you need to move tableName out of attributes, since it's a class-level property. Second, sails-postgresql does have some (very undocumented) support for schemas, using the meta.schemaName option:
Movie = {
tableName: 'movies',
meta: {
schemaName: 'movie'
},
attributes: {
title: 'string',
link: 'string'
}
};
module.exports = Movie;
You can give that a try, and if it doesn't work, either move your table into the public schema, or nudge the author of the schemaName support for help.