GraphQL - passing an ObjectType a parameter - node.js

I'm using GraphQL and it's working great, however, I can't seem to figure out how to pass a parameter into the fields section of my Event GraphQLObjectType.
I would like to be able to pass in the currentUserId (which is given to me through a token) into the Event GraphQLObjectType so I can add in an isAttending attribute.
I've attached code with comments of what I'm basically trying to do:
const Event = new GraphQLObjectType({
name: 'Event',
description: 'This represents an Event',
fields: (currentUserId) => { // currentUserId is the parameter I would like to pass in
return {
id: {
type: GraphQLInt,
resolve (event) {
return event.id;
}
},
title: {
type: GraphQLString,
resolve (event) {
return event.title;
}
},
attendees: {
type: new GraphQLList(User),
resolve (event) {
return event.getAttendees()
}
},
// this is what I would like to do
isAttending: {
type: GraphQLBool,
resolve (event) {
return event.getAttendees({
where: {
id: currentUserId // that's the parameter I would like pass in
}
}).then(attendee => {
return (attendee.length > 0 ? true : false);
)};
}
}
// end of what I'm trying to do //
};
}
});
const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields: () => {
return {
events: {
type: new GraphQLList(Event),
args: {
id: {
type: GraphQLInt
}
},
resolve (root, args) {
// here is the parameter I would like to pass to the event object
let currentUserId = root.userId;
////////
return Db.models.event.findAll({ where: args });
}
},
...
Update
The reason I can't just do data.currentUserId = root.userId, is because it's not visible when I'm returned a collection of event objects, since what is passed into my Event GraphQLOBjectType is only the {event} object.
What it looks like when I do data.currentUserId and there is an array of objects inside data is this:
[{objects}, currentUserId: 1]
As opposed to what we want which is this:
[{object, currentUserId: 1}, {anotherObject, currentUserId: 1}]
If I wanted to have access to the currentUserId in the Event GraphQLObject, the only thing I can think of is to loop through every object and add the currentUserId onto it like this:
return events.map(event => {
event.currentUserId = currentUserId;
return event;
});`
Is this the best solution?

I'm afraid you can't do that. fields doesn't recieve any parameters, so you won't send any either.
Fortunately, you can achieve that in more convenient way.
Everything your parent type (Query) returns in resolve function is visible in child resolve's root parameter.
const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields: () => ({
events: {
type: new GraphQLList(Event),
args: {
id: {
type: GraphQLInt
}
},
resolve (root, args) {
return Db.models.event.findAll({ where: args })
.then(data => {
// pass the parameter here
data.currentUserId = root.userId;
return data;
});
}
},
...
Then your Event object would look like this:
const Event = new GraphQLObjectType({
name: 'Event',
description: 'This represents an Event',
fields: () => ({
...
isAttending: {
type: GraphQLBool,
resolve: (event) => {
return event.getAttendees({
where: {
id: event.currentUserId // that's the parameter you've passed through parent resolve
}
}).then(attendee => {
return (attendee.length > 0 ? true : false);
});
}
}
})
});

Related

How to update Elasticsearch dynamic data multiple fields using UpdateByQuery in NodeJS

How to update Elasticsearch data multiple fields using UpdateByQuery in NodeJS ?
Note - My data is coming dynamically. I can't pass static value. I have to pass like - data.name, data.id
Code -
function updateInELK(data) { // Update by Id
const updateScript = {
inline: {
"ctx._source.name = "+data.name,
"ctx._source.role = "+data.role,
};
return new Promise((resolve, reject) => {
elasticsearch.updateByQuery({
index: indexName,
body: {
query: { match: { id: data.id } },
script: updateScript,
lang: 'painless',
}
}).then((response) => {
resolve(response);
}).catch((err) => {
console.log(err);
reject("Elasticsearch ERROR - data not updated")
})
});
}
Error -
TypeError: "ctx._source.name = " is not a function
Please let me know, if any other options are there. I can't update using id, because I don't know the id. I wanted to use updateByQuery, with conditions in the query parameters.
Here are the solutions -
await esClient.updateByQuery({
index: "data",
type: "doc",
refresh: true,
body:{
query:{
match: {
dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
}
},
script:{
lang:"painless",
source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=params.date;ctx._source.segmentId=params.segmentId`,
params:{
date: Date.now(),
segmentId: null
}
}
}
});

How to stub query helper method Mongoose?

I'm using Sinon to test my Express/Typescript application. In Mongoose I have models with query helper methods to make query chains.
I have this schema
export const articuloSchema = new Schema({
_id: { type: String, default: v4 },
numeroInventario: { type: String, required: true, unique: true },
descripcion: { type: String, trim: true },
}, {
versionKey: false,
query: {
paginate(page: number, limit: number) {
return this.skip(page - 1).limit(limit);
}
}
});
export type ArticuloType = InferSchemaType<typeof articuloSchema>;
export const Articulo = mongoose.model('Articulo', articuloSchema);
and I want to fake my query helper method with Sinon like this
const getMultipleArticulos (): ArticuloType[] => {
const arr:ArticuloType = []
for (let i = 0; i < 5; i++) {
arr.push({
numeroInventario: i,
descripcion: 'string'
})
}
return arr;
}
it('Should return a list of items that belong to a user', function (done) {
const paginateFake = sinon.fake.resolves(getMultipleArticulos());
sinon.replace(Articulo, 'paginate', paginateFake);
chai.request(app)
.get(`/api/v1/users/${userId}/articulos`)
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(200);
// more expects
done();
});
});
The problem is that I cannot stub those methods, it says that it can't stub non existent property of 'paginate' (which is the query helper method I added to my model).

Unable to get initial data using graphql-ws subscription

I am fairly new to using graphql-ws and graphql-yoga server, so forgive me if this is a naive question or mistake from my side.
I went through graphql-ws documentation. It has written the schema as a parameter. Unfortunately, the schema definition used in the documentation is missing a reference.
After adding a new todo (using addTodo) it shows two todo items. So I believe it is unable to return the initial todo list whenever running subscribe on Yoga Graphiql explorer.
It should show the initial todo item as soon as it has been subscribed and published in the schema definition.
My understanding is there is something I am missing in the schema definition which is not showing the todo list when tried accessing Yoga Graphiql explorer.
Has anyone had a similar experience and been able to resolve it? What I am missing?
Libraries used
Backend
graphql-yoga
ws
graphql-ws
Frontend
solid-js
wonka
Todo item - declared in schema
{
id: "1",
title: "Learn GraphQL + Solidjs",
completed: false
}
Screenshot
Code Snippets
Schema definition
import { createPubSub } from 'graphql-yoga';
import { Todo } from "./types";
let todos = [
{
id: "1",
title: "Learn GraphQL + Solidjs",
completed: false
}
];
// channel
const TODOS_CHANNEL = "TODOS_CHANNEL";
// pubsub
const pubSub = createPubSub();
const publishToChannel = (data: any) => pubSub.publish(TODOS_CHANNEL, data);
// Type def
const typeDefs = [`
type Todo {
id: ID!
title: String!
completed: Boolean!
}
type Query {
getTodos: [Todo]!
}
type Mutation {
addTodo(title: String!): Todo!
}
type Subscription {
todos: [Todo!]
}
`];
// Resolvers
const resolvers = {
Query: {
getTodos: () => todos
},
Mutation: {
addTodo: (_: unknown, { title }: Todo) => {
const newTodo = {
id: "" + (todos.length + 1),
title,
completed: false
};
todos.push(newTodo);
publishToChannel({ todos });
return newTodo;
},
Subscription: {
todos: {
subscribe: () => {
const res = pubSub.subscribe(TODOS_CHANNEL);
publishToChannel({ todos });
return res;
}
},
},
};
export const schema = {
resolvers,
typeDefs
};
Server backend
import { createServer } from "graphql-yoga";
import { WebSocketServer } from "ws";
import { useServer } from "graphql-ws/lib/use/ws";
import { schema } from "./src/schema";
import { execute, ExecutionArgs, subscribe } from "graphql";
async function main() {
const yogaApp = createServer({
schema,
graphiql: {
subscriptionsProtocol: 'WS', // use WebSockets instead of SSE
},
});
const server = await yogaApp.start();
const wsServer = new WebSocketServer({
server,
path: yogaApp.getAddressInfo().endpoint
});
type EnvelopedExecutionArgs = ExecutionArgs & {
rootValue: {
execute: typeof execute;
subscribe: typeof subscribe;
};
};
useServer(
{
execute: (args: any) => (args as EnvelopedExecutionArgs).rootValue.execute(args),
subscribe: (args: any) => (args as EnvelopedExecutionArgs).rootValue.subscribe(args),
onSubscribe: async (ctx, msg) => {
const { schema, execute, subscribe, contextFactory, parse, validate } =
yogaApp.getEnveloped(ctx);
const args: EnvelopedExecutionArgs = {
schema,
operationName: msg.payload.operationName,
document: parse(msg.payload.query),
variableValues: msg.payload.variables,
contextValue: await contextFactory(),
rootValue: {
execute,
subscribe,
},
};
const errors = validate(args.schema, args.document);
if (errors.length) return errors;
return args;
},
},
wsServer,
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
apply these changes
Mutation: {
addTodo: (_: unknown, { title }: Todo) => {
const newTodo = {
id: "" + (todos.length + 1),
title,
completed: false
};
todos.push(newTodo);
publishToChannel({ todos });
return newTodo;
},
Subscription: {
todos: {
subscribe: () => {
return Repeater.merge(
[
new Repeater(async (push, stop) => {
push({ todos });
await stop;
}),
pubSub.subscribe(TODOS_CHANNEL),
]
)
}
},
},
first, npm i #repeaterjs/repeater then import Repeater

Issue setting up subscription with GraphQL

Good day:
I"m trying to setup my graphql server for a subscription. This is my schema.js
const ChatCreatedSubscription = new GraphQLObjectType({
name: "ChatCreated",
fields: () => ({
chatCreated: {
subscribe: () => pubsub.asyncIterator(CONSTANTS.Websocket.CHANNEL_CONNECT_CUSTOMER)
}
})
});
const ChatConnectedSubscription = {
chatConnected: {
subscribe: withFilter(
(_, args) => pubsub.asyncIterator(`${args.id}`),
(payload, variables) => payload.chatConnect.id === variables.id,
)
}
}
const subscriptionType = new GraphQLObjectType({
name: "Subscription",
fields: () => ({
chatCreated: ChatCreatedSubscription,
chatConnected: ChatConnectedSubscription
})
});
const schema = new GraphQLSchema({
subscription: subscriptionType
});
However, I'm getting this error when I try to run my subscription server:
ERROR introspecting schema: [
{
"message": "The type of Subscription.chatCreated must be Output Type but got: undefined."
},
{
"message": "The type of Subscription.chatConnected must be Output Type but got: undefined."
}
]
A field definition is an object that includes these properties: type, args, description, deprecationReason and resolve. All these properties are optional except type. Each field in your field map must be an object like this -- you cannot just set the field to a type like you're doing.
Incorrect:
const subscriptionType = new GraphQLObjectType({
name: "Subscription",
fields: () => ({
chatCreated: ChatCreatedSubscription,
chatConnected: ChatConnectedSubscription
})
});
Correct:
const subscriptionType = new GraphQLObjectType({
name: "Subscription",
fields: () => ({
chatCreated: {
type: ChatCreatedSubscription,
},
chatConnected: {
type: ChatConnectedSubscription,
},
})
});
Check the docs for additional examples.

How to execute a mutation in GraphQL?

In GraphQL we have basically two types of operations: queries and mutations. While queries are well described in the documentation and there are many examples of them, I'm having a hard time to understand how to execute a mutation. Mutations obviously are update methods.
I've created very simple Node.js server:
var express = require("express");
var graphqlHTTP = require("express-graphql");
var graphql = require("graphql");
var inMemoryDatabase = require("./inMemoryDatabase").inMemoryDatabase;
var _ = require("lodash-node");
var userType = new graphql.GraphQLObjectType({
name: "User",
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
}
});
var queryType = new graphql.GraphQLObjectType({
name: "Query",
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: function(parent, { id }) {
return _.find(inMemoryDatabase, { id: id });
}
}
}
});
var mutationType = new graphql.GraphQLObjectType({
name: "Mutation",
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
},
resolve: function(parent, { id, name }) {
var index = _.findIndex(inMemoryDatabase, { id: id });
inMemoryDatabase.splice(index, 1, { id: id, name: name });
return _.find(inMemoryDatabase, { id: id });
}
}
}
});
var schema = new graphql.GraphQLSchema({
query: queryType,
mutation: mutationType
});
var app = express();
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true
})
);
var port = 9000;
if (process.env.PORT) {
port = process.env.PORT;
}
app.listen(port);
console.log("Running a GraphQL API server at localhost:" + port + "/graphql");
In memory database is just in an array of User objects {id, name}:
var inMemoryDatabase = [
{
id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8",
name: "Mark"
},
{
id: "2fb6fd09-2697-43e2-9404-68c2f1ffbf1b",
name: "Bill"
}
];
module.exports = {
inMemoryDatabase
};
Executing query to get user by id looks as follows:
{
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8"){
name
}
}
How would the mutation changing user name look like?
Hey may completely be missing what you are saying, but the way that I look at a mutation is like this
I get some arguments and a field, that is the same thing as params and a path in rest, with those i do something (in your case lookup the user and update the attribute based on the arguments passed in
After That, i return something from the resolve function that will fulfill the type you specify in the type of the mutation
var mutationType = new graphql.GraphQLObjectType({
name: "Mutation",
fields: {
user: {
// You must return something from your resolve function
// that will fulfill userType requirements
type: userType,
// with these arguments, find the user and update them
args: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString }
},
// this does the lookup and change of the data
// the last step of your result is to return something
// that will fulfill the userType interface
resolve: function(parent, { id, name }) {
// Find the user, Update it
// return something that will respond to id and name, probably a user object
}
}
}
});
Then with that as a context, you pass some arguments and request back a user
mutation updateUser {
user(id: "1", name: "NewName") {
id
name
}
}
In a normal production schema you would also normally have something like errors that could be returned to convey the different states of the update for failed/not found
#Austio's answer was pretty close, but the proper way is:
mutation updateUser {
user(id: "31ce0260-2c23-4be5-ab78-4a5d1603cbc8", name: "Markus") {
id
name
}
}
if we connect directly with MongoDB below will help you.
mutation {
taskTrackerCreateOne
(
record:
{
id:"63980ae0f019789eeea0cd33",
name:"63980c86f019789eeea0cda0"
}
)
{
recordId
}
}

Resources