GraphQL mutation that accepts an array of dynamic size in one request as input with NodeJs - node.js

I want to pass an object array of [{questionId1,value1},{questionId2,value2},{questionId3,value3}] of dynamic size in GraphQL Mutation with NodeJS
.........
args: {
input: {
type: new GraphQLNonNull(new GraphQLInputObjectType({
name: 'AssessmentStep3Input',
fields: {
questionId:{
name:'Question ID',
type: new GraphQLNonNull(GraphQLID)
},
value:{
name:'Question Value',
type: new GraphQLNonNull(GraphQLBoolean)
}
}
}))
}
},
.........
How can I do that with the given sample of code?
Thanks

If you want to pass an object array with GraphQL Mutation you need to use "GraphQLList" which allows you to pass an array with dynamic size of given input.
Here is the example
........
........
args: {
input: {
type: new GraphQLNonNull(GraphQLList(new GraphQLInputObjectType({
name: 'AssessmentStep3Input',
fields: {
questionId:{
name:'Question ID',
type: new GraphQLNonNull(GraphQLID)
},
value:{
name:'Question Value',
type: new GraphQLNonNull(GraphQLBoolean)
}
}
}))
)
}
},
........
........
Hope it helps.
Thanks

i just published the article on that, so that you can take a look if you would like to know more detail. This is the repository with the examples, where the createUsers mutation is implemented https://github.com/atherosai/express-graphql-demo/blob/feature/5-modifiers/server/graphql/users/userMutations.js. You can take a look how it is implemented, but in general the above answer is correct. You can input as many objects as you would like to in the array (if you have not implemented some number of items limiting, but it is not there by default).

Related

Storing and querying JSON arrays in Redisjson with nodejs

What I was hoping to do was store an array of objects using RedisJSON very simply and then query that array.
I have something similar to this:
const data = [
{
_id: '63e7d1d85ad7e2f69df8ed6e',
artist: {
genre: 'rock',
},
},
{
_id: '63e7d1d85ad7e2f69df8ed6f',
artist: {
genre: 'metal',
},
},
{
_id: '63e7d1d85ad7e2f69df8ed6g',
artist: {
genre: 'rock',
},
},
]
then I can easily store and retrieve this:
await redisClient.json.set(cacheKey, '$', data)
await redisClient.json.get(cacheKey)
works great. but now I want to also query this data, I've tried creating an index as below:
await redisClient.ft.create(
`idx:gigs`,
{
'$.[0].artist.genre': {
type: SchemaFieldTypes.TEXT,
AS: 'genre',
},
},
{
ON: 'JSON',
PREFIX: 'GIGS',
}
)
and when I try and search this index what I expect is it to return the 2 documents with the correct search filter, but instead it always returns the entire array:
const searchResult = await redisClient.ft.search(`idx:gigs`, '#genre:(rock)')
produces:
{
total: 1,
documents: [
{ id: 'cacheKey', value: [Array] }
]
}
I can't quite work out at which level I'm getting this wrong, but any help would be greatly appreciated.
Is it possible to store an array of objects and then search the nested objects for nested values with RedisJSON?
The Search capability in Redis stack treats each key containing a JSON document as a separate search index entry. I think what you are doing is perhaps storing your whole array of documents in a single Redis key, which means any matches will return the document at that key which contains all of your data.
I would suggest that you store each object in your data array as its own key in Redis. Make sure that these will be indexed by using the GIGS prefix in the key name, for example GIGS:63e7d1d85ad7e2f69df8ed6e and GIGS:63e7d1d85ad7e2f69df8ed6f.
You'd want to change your index definition to account for each document being an object too so it would look something like this:
await redisClient.ft.create(
`idx:gigs`,
{
'$.artist.genre': {
type: SchemaFieldTypes.TEXT,
AS: 'genre',
},
},
{
ON: 'JSON',
PREFIX: 'GIGS:',
}
)
Note I also updated your PREFIX to be GIGS: not GIGS - this isn't strictly necessary, but does stop your index from accidentally looking at other keys in Redis whose name begins GIGS<whatever other characters>.

Sequelize setter error 'invalid input syntax for integer: "[object Object]"'

I am trying to associate a list of contacts to a customer using the associations setter method, however, it always throws the error 'invalid input syntax for integer: "[object Object]"'.
The relevant query mentioned in the error is: UPDATE "contactperson" SET "refCustomerId"=$1,"updatedAt"=$2 WHERE "id" IN ('[object Object]')
This is how I use the setter:
db.customer.findByPk(customerID, {
include: [{
model: db.address,
as: 'address',
},{
model: db.contactoption,
as: 'contactOptions',
}, {
model: db.contactperson,
as: 'contactPersons',
}]
}).then(customer => {
customer.setContactPersons([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]);
});
This is the association:
Customer.hasMany(models.contactperson, {
foreignKey: 'refCustomerId',
as: 'contactPersons'
});
Any idea what I'm doing wrong?
I managed to resolve this issue using the following code:
db.contactperson.bulkCreate([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]).then(newContactPersons => {
customer.setContactPersons(newContactPersons);
});
It's a more complicated approach than intended, but it get's the job done.
You used set<ModelName>s that just updates a link field of given records. If you need to create contactperson record you need to use createContactPerson instead of setContactPersons (NOTE: you cannot create several records at once).
customer.createContactPerson({
firstName: 'tester',
lastName: 'tester',
description: 'lorem ipsum'
});
compare to:
const contactPerson = db.contactperson.findById(1);
if (contactPerson) {
customer.addContactPersons([contactPerson.id]);
}
set<ModelName>s - replaces old linked records with the new existing ones
add<ModelName>s - adds exisiting records in addition to old ones
create<ModelName> - create a new non-existing record in addition to old ones
See hasMany special methods
Exactly what Anatoly posted.
I had method declared on TypeScript like:
declare addPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;
When i changed to:
declare createPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;
Everything works so remember - how you describe name of method its very necesary.

Mongoose create new data with incremented index-like field

What I want to do:
Whenever I add a new item to the collection (in my case a game), it will have a incremented "index"-like value (in my case I'm naming it index too).
My games collection should looks like:
[
{ "index":0, ... data }
{ "index":1, ... data }
{ "index":2, ... data }
]
The term is so hard to search. I always end up with:
$inc for update. Not this, I want to have incremented number on create.
Schema.index does look like what I want, but somehow it doesn't work at all:
const gameModel = new Schema({
index: {
type: Number,
default: 0
},
players: [{
name: String,
score: Number
}]
}, {
timestamps: {
createdAt: 'date'
}
});
gameModel.index({
index: 1
});
With this I always get index: 0. If I turn off default no index is created.
What do I do now? (I would prefer to keep the _id intact)
You can use a npm package named mongoose-auto-increment which provides this functionality. It is also very easy and well documented

Sequelize is returning integer as string

I using nodejs v4 with sequelize, and I have a model like this:
var Device = sequelize.define('Device', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true
},
tenantId: {
type: DataTypes.BIGINT,
allowNull: false
},
token: {
type: DataTypes.STRING,
allowNull: false
}
}, {
tableName: 'devices'
});
When I select a device by id the type of id is a string, exemple:
Device.findById(9).then( function(result) {
console.log(result.toJSON().id + 10);
});
The output will be 910, rather than 19, so I look at json and a saw this:
{
id: "9"
tenantId: "123"
token: "adsadsdsa"
}
The id in found device is a string, but I defined it as a number...
Doesn't it should be { "id": 9 } ?
How can I select a device with the types that I defined previously?
BIGINT maximum value is 2^63-1, javascript can safely represent up to 2^53. To be on the safe side libraries return those numbers as strings.
If you want to have numbers instead of strings, you can use this library https://github.com/mirek/node-pg-safe-numbers which deals with this issue.
I found a fix to this problem on sequelize repo.
https://github.com/sequelize/sequelize/issues/4523
The pg module used for sequelize returns bigint as string because bigints are not guaranteed to fit into js numbers. So I change my model to use integer (DataTypes.INTEGER)
IMO, a smoother solution is to force parsing of int to int, instead of strings. Checkout this issue and comments.
Trying to put this line before your logic code worked for me, this forces parsing of int8 to int, instead of strings:
require("pg").defaults.parseInt8 = true;
...
try {
const list = await Posts.findAll();
console.log(JSON.stringify(list));
} catch (e) {
console.log(e.message);
}
By default, sequelize try format your results. You can set raw :true for get raw data

What is the difference between "describe" and "schema.define"?

As I've progressed thru the world of CompoundJS I've came across two ways of defining a schema:
First:
var Product = describe('Product', function () {
property('upc', String);
property('name', String);
set('restPath', pathTo.products);
});
Second:
var Schema = require('jugglingdb').Schema;
var schema = new Schema('memory');
var Product = schema.define('Product', {
upc: { type: Number, index: true },
name: { type: String, limit: 150, index: true },
createdAt: { type: Date, default: Date.now },
modifiedAt: { type: Date, default: Date.now }
}, {
restPath: pathTo.products
});
The first, works, but looks like an old design. The second, does not work, but this is the way to do it according to JugglingDB docs.
Which one should I use? Why wouldn't the second one work for me?
UPDATE:
This is the error I get when I use the second one:
Express
500 TypeError: Cannot call method 'all' of undefined in products controller during "index" action
at Object.index (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\app\controllers\products.js:47:13)
at Array.2 (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\flow-control.js:150:28)
at ActionContext.run [as innerNext] (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\flow-control.js:103:31)
at Controller.BaseController.next (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\base.js:107:22)
at Controller.protectFromForgery (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\helpers.js:76:21)
at Object.protectFromForgeryHook (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\app\controllers\application.js:3:13)
at Array.1 (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\flow-control.js:150:28)
at run (C:\Users\Eran\Documents\Relay Foods\nutrition-facts-editor\node_modules\compound\node_modules\kontroller\lib\flow-control.js:103:31)
... snip ...
I think that describe and define are the same. The issue here is the usage scope which is global in my first implementation and local in the second one. So I'll need it to be global in order to work with the rest of the application.

Resources