GraphQL - does context propagate to downstream resolvers? - graphql

If you pass a modified context to a GraphQL resolver does this propagate to all downstream resolvers? Is this specified in the GraphQL specification or implementation specific?
To clarify with an example say I have a query like the following
{
companies {
employees {
positions {
title
}
}
}
}
let's say I start with contextA coming into the companies query and then I have my CompanyResolvers where I get a superSpecialContext and pass this on to the employees dataloader
export const CompanyResolvers = {
employees: async ({ id }: CompanyDTO, args: object, contextA: Context) => {
const superSpecialContext = await getSuperSpecialContext();
return context.dataLoaders.employees.load({ id: company.id, context: superSpecialContext });
}
};
when I get to the positions resolver am I now working with the superSpecialContext or the original contextA (I would actually prefer this to be the case)?
export const EmployeeResolvers = {
positions: async ({ id }: EmployeeDTO, args: object, context: Context) => {
// is my context here contextA or superSpecialContext?
}
};

If you pass a modified context to a GraphQL resolver does this propagate to all downstream resolvers.
Yes, each request gets its own context object for the duration of the request. It gets created in the context function on the GraphQL server.
import { ApolloServer, gql } from 'apollo-server'
import { ExpressContext } from 'apollo-server-express/dist/ApolloServer';
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const resolvers = {
Query: {
books: (obj: any, args: any, context: any) => {
console.log(context.name); // Khalil Stemmler
context.name = 'Billy Bob Thorton'
return books;
},
},
Book: {
title: (obj: any, args: any, context: any) => {
console.log(context.name); // Billy Bob Thorton.
// Should print "Billy Bob Thorton twice", once for each book.
return obj.title
},
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: (expressContext: ExpressContext) => {
// The Apollo implementation of context allows you hook into the
// Express request to get access to headers, tokens, etc- in order
// to grab an authenticated user's session data and put it on context.
const { connection, res, req } = expressContext;
// A new context object is created for every request. This function
// should return an object.
return {
name: 'Khalil Stemmler'
}
}
});
// The `listen` method launches a web server.
server.listen().then(({ url }: { url: string }) => {
console.log(`🚀 Server ready at ${url}`);
});
Running the following query:
{
books {
title
author
}
}
We get:
🚀 Server ready at http://localhost:4000/
Khalil Stemmler
Billy Bob Thorton
Billy Bob Thorton
Reference: "Context Argument - Apollo Docs".

Related

GraphQL How to properly implement chain resolvers?

One of the main concepts of GraphQL is being able to select the data we're interested in, while omitting the unnecessary fields. To achieve that we can use resolvers. Each such is responsible for providing data for a particular type.
I've created a small example to present my problem.
The error it returns is:
"Cannot return null for non-nullable field Parent.child."
I could just let the Parent create the whole object, but then where's the benefit of resolving delegation, what would be the point of creating the Child resolver and then the whole GraphQL concept of resolver chains?
How to make the parent call the Child resolver to resolve its child field?
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Child {
name: String!
}
type Parent {
name: String!
child: Child!
}
type Query {
getParent: Parent!
}
`;
(async function () {
const server = new ApolloServer({
typeDefs,
resolvers: {
Query: {
getParent: () => {
return {
name: "parent",
};
},
},
Child: {
name: () => "child",
},
}
});
await server.listen();
})();
Here is how you should write your resolver:
import { gql,ApolloServer } from "apollo-server";
const typeDefs = gql`
type Child {
name: String!
}
type Parent {
name: String!
child: Child!
}
type Query {
getParent: Parent!
}
`;
(async function () {
const server = new ApolloServer({
typeDefs,
resolvers: {
Query: {
getParent: () => {
return {
name: "parent",
};
},
},
Parent: {
child: () => {
return {
name: "child",
}
}
},
}
});
await server.listen().then(({url}) => {
console.log(url)
});
})();
I'm also a beginner in gql, but I will give my thoughts.
When you define a new ObjectType:Parent, you should write the ObjectField Resolver for it if you have nested ObjectType, which means you should write the resolver specific the Object and its child's resolver function. that way , the nested object could found the way to fetch the data.
The Query and Mutation is just two special entry point.
refer to this: https://graphql.org/learn/schema/#the-query-and-mutation-types

How to run a mutation in ApolloServer using the GraphQL Playground?

I'm using node.js, express and apollo-server-express. With the following code:
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = gql`
type Book { title: String author: String }
type Query { books: [Book] }
type Mutation { change_title(new_title: String): Book }
`;
const books = [
{ title: 'The Awakening', author: 'Kate Chopin', },
{ title: 'City of Glass', author: 'Paul Auster', },
];
const resolvers = {
Query: { books: () => books, },
Mutation: {
change_title: (parent, args) => {
books[0].title = args.new_title
return books[0]
}
}
};
const server = new ApolloServer({ typeDefs, resolvers, });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
);
When I enter the mutation in the GraphQL Playground, like so:
{
change_title(new_title: "Something") {
title
}
}
I get the following error: "Cannot query field "change_title" on type "Query"."
My goal is to be able to run mutations. If I should be doing it another way or if there's eror, please let me know. Thanks!
GraphQL playground treats all types as queries unless otherwise specified.
mutation {
change_title(new_title: "Something") {
title
}
}

Data not returned from REST datasource in Apollo server for graphQL

I am trying out the basic implementation for Apollo server for GraphQL with my REST API calls as Data Sources. I do not see any data returned from the same even though there is data returned when I call the API separately. Can anyone help figure out what could be going wrong?
PS: I have CORS enabled on my API so not sure if I am passing that too correctly. I do not have any idea how to figure out what URL this is calling.
My sample code below:
const { ApolloServer, gql } = require('apollo-server');
const { RESTDataSource } = require('apollo-datasource-rest');
class Contact extends RESTDataSource {
constructor() {
super();
this.baseURL = 'http://localhost:8080/objects/';
}
async getContactById(id) {
return this.get(`contact/${id}`);
}
async getAllContacts() {
const data = await this.get(`contact`);
return data.results;
}
// an example making an HTTP PUT request
async newContact(contact) {
return this.put(
'contact', // path
contact, // request body
);
}
};
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
# Comments in GraphQL are defined with the hash (#) symbol.
type Query {
allContacts: [Contact]
contactById(id: ID): Contact
}
type Contact {
id: ID
contact_name: String
}
`;
// Resolvers define the technique for fetching the types in the
// schema.
const resolvers = {
Query: {
contactById: async (_source, { id }, { dataSources }) => {
return dataSources.contact.getContactById(id);
},
allContacts: async (_source, _args, { dataSources }) => {
return dataSources.contact.getAllContacts();
},
},
};
// In the most basic sense, the ApolloServer can be started
// by passing type definitions (typeDefs) and the resolvers
// responsible for fetching the data for those types.
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
contact : new Contact(),
};
},
cors : true,
});
// This `listen` method launches a web-server. Existing apps
// can utilize middleware options, which we'll discuss later.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
Below is the request and response from the GraphQL playground:
query {
contactById (id : 5) {
id
contact_name
}
}
Response:
{
"data": {
"contactById": {
"id": null,
"contact_name": null
}
}
}

graphql-subscriptions withFilter returns undefined; subscriptions without variables work ok

I'm trying to get my head around graphql-subscriptions and withFilter. Subscriptions without variables work as intended, but if I try to use withFilter, I only get 'Subscription field must return Async Iterable. Received: undefined' error when I try to run the subscription.
Am I doing something wrong with setting up withFilter, are the some incompatibilities with packages I'm using or am I completely missing something obvious here? All queries and mutations work properly, so the basic set up should be fine.
My set up is similar to this (all code snippets are in https://gist.github.com/aqmattil/41e10e7c9f30b8ea964cecdc61c58f20
Package.json
// package.json
"dependencies": {
"apollo-server-express": "^2.0.0-beta.2",
"body-parser": "^1.18.3",
"express": "^4.16.3",
"graphql": "^0.13.2",
"graphql-subscriptions": "^0.5.8",
"subscriptions-transport-ws": "^0.9.11"
}
Mutations
// mutations.js
const mutation = new GraphQLObjectType({
name: 'mutation',
fields: {
addSite: {
type: SiteType,
description: "Create a new Site",
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
location: { type: GraphQLString },
company: { type: GraphQLString }
},
async resolve(parentValue, { name, location, company }) {
const site = await new Site({ name, location, company }).save()
const siteid = site._id;
console.log("addSite resolve", siteid, name, location, company );
pubsub.publish('siteAdded', { 'siteAdded': site } );
return site;
}
}
}
});
module.exports = mutation;
Subscriptions
// subscriptions.js
const graphql = require('graphql');
const {
GraphQLObjectType,
GraphQLString
} = graphql;
const { withFilter } = require('graphql-subscriptions');
const SiteType = require('./site_type');
const pubsub = require('./pubsub_helper');
const Subscriptions = new GraphQLObjectType({
name: 'subscription',
fields: () => ({
/*
// this code works, commented out to test withfilter
siteAdded: {
type: SiteType,
resolve(payload) {
return payload.siteAdded;
},
subscribe() {
return pubsub.asyncIterator('siteAdded');
}
},
*/
// test withFilter
siteAdded: {
type: SiteType,
args: {
name: { type: GraphQLString }
},
resolve(payload) {
return payload.siteAdded;
},
subscribe() {
// this returns undefined
withFilter(
() => {
console.log("in subscribe withfilter");
return pubsub.asyncIterator('siteAdded');
}
),
(payload, variables) => {
console.log("payload, variables", payload, variables);
return true;
}
}
}
})
});
module.exports = Subscriptions;
I'm using graphiql to run the queries,
// this is used to add a site
mutation {
addSite(name:"test name", location: "somewhere") {
id
}
}
// simple subscription - this works as inteded, and new sites are shown
subscription {
siteAdded {
name
location
company {
id
}
}
}
// using query variables --> returns "Subscription
// field must return Async Iterable. Received: undefined"
subscription {
siteAdded(name: "test name") {
name
location
company {
id
}
}
}

Apollo GraphQL server; setting context to handle requests triggered by a fired subscription

I understand how to set the context object when creating a GraphQL server e.g.
const app = express();
app.use(GRAPHQL_URL, graphqlExpress({
schema,
context: {
foo: 'bar'
},
}));
so that the context object is passed to my resolvers when handling an incoming request.
However I'm not seeing this context object when the resolvers are triggered by a subscription (i.e. a client subscribes to a GraphQL subscription, and defines the shape of the data to be sent to them when the subscription fires); in that case the context appears to be an empty Object.
Is there way to ensure that my context object is set correctly when resolvers are called following a PubSub.publish() call?
I guess you are using the package subscription-transport-ws. In that case it is possible to add a context value in different execution steps.
See API. Two possible scenarios
If you have some kind of authentication. You could add a viewer in the context at the onConnect execution step. This is done at the first connection to the websocket and wont change until the connection is closed and opened again. See example.
If you want to add a context more dynamically you can add a kind of middleware before the execute step.It could look like this:
const middleware = (args) => new Promise((resolve, reject) => {
const [schema, document, root, context, variables, operation] = args;
context.foo = "bar"; // add something to context
resolve(args);
})
subscriptionServer = SubscriptionServer.create({
schema: executable.schema,
subscribe,
execute: (...args) => middleware(args).then(args => {
return execute(...args);
})
}, {
server: websocketServer,
path: "/graphql",
}, );
Here is my solution:
You can pass the context and do the authentication for graphql subscription(WebSocket )like this:
const server = new ApolloServer({
typeDefs,
resolvers,
context: contextFunction,
introspection: true,
subscriptions: {
onConnect: (
connectionParams: IWebSocketConnectionParams,
webSocket: WebSocket,
connectionContext: ConnectionContext,
) => {
console.log('websocket connect');
console.log('connectionParams: ', connectionParams);
if (connectionParams.token) {
const token: string = validateToken(connectionParams.token);
const userConnector = new UserConnector<IMemoryDB>(memoryDB);
let user: IUser | undefined;
try {
const userType: UserType = UserType[token];
user = userConnector.findUserByUserType(userType);
} catch (error) {
throw error;
}
const context: ISubscriptionContext = {
// pubsub: postgresPubSub,
pubsub,
subscribeUser: user,
userConnector,
locationConnector: new LocationConnector<IMemoryDB>(memoryDB),
};
return context;
}
throw new Error('Missing auth token!');
},
onDisconnect: (webSocket: WebSocket, connectionContext: ConnectionContext) => {
console.log('websocket disconnect');
},
},
});
You can pass the context argument of resolver using pubsub.publish method in your resolver like this:
addTemplate: (
__,
{ templateInput },
{ templateConnector, userConnector, requestingUser }: IAppContext,
): Omit<ICommonResponse, 'payload'> | undefined => {
if (userConnector.isAuthrized(requestingUser)) {
const commonResponse: ICommonResponse = templateConnector.add(templateInput);
if (commonResponse.payload) {
const payload = {
data: commonResponse.payload,
context: {
requestingUser,
},
};
templateConnector.publish(payload);
}
return _.omit(commonResponse, 'payload');
}
},
Now, we can get the http request context and subscription(websocket) context in
your Subscription resolver subscribe method like this:
Subscription: {
templateAdded: {
resolve: (
payload: ISubscriptionPayload<ITemplate, Pick<IAppContext, 'requestingUser'>>,
args: any,
subscriptionContext: ISubscriptionContext,
info: any,
): ITemplate => {
return payload.data;
},
subscribe: withFilter(templateIterator, templateFilter),
},
},
async function templateFilter(
payload?: ISubscriptionPayload<ITemplate, Pick<IAppContext, 'requestingUser'>>,
args?: any,
subscriptionContext?: ISubscriptionContext,
info?: any,
): Promise<boolean> {
console.count('templateFilter');
const NOTIFY: boolean = true;
const DONT_NOTIFY: boolean = false;
if (!payload || !subscriptionContext) {
return DONT_NOTIFY;
}
const { userConnector, locationConnector } = subscriptionContext;
const { data: template, context } = payload;
if (!subscriptionContext.subscribeUser || !context.requestingUser) {
return DONT_NOTIFY;
}
let results: IUser[];
try {
results = await Promise.all([
userConnector.findByEmail(subscriptionContext.subscribeUser.email),
userConnector.findByEmail(context.requestingUser.email),
]);
} catch (error) {
console.error(error);
return DONT_NOTIFY;
}
//...
return true;
}
As you can see, now we get the subscribe users(who establish the WebSocket connection with graphql webserver) and HTTP request user(who send the mutation to graphql webserver) from subscriptionContext and HTTP request context.
Then you can do the rest works if the return value of templateFilter function is truthy, then WebSocket will push message to subscribe user with payload.data, otherwise, it won't.
This templateFilter function will be executed multiple times depending on the count of subscribing users which means it's iterable. Now you get each subscribe user in this function and does your business logic to decide if push WebSocket message to the subscribe users(client-side) or not.
See github example repo
Articles:
GraphQL Subscription part 1
GraphQL Subscription part 2
If you're using Apollo v3, and graphql-ws, here's a docs-inspired way to achieve context resolution:
const wsContext = async (ctx, msg, args) => {
const token = ctx.connectionParams.authorization;
const currentUser = await findUser(token);
if(!currentUser) throw Error("wrong user token");
return { currentUser, foo: 'bar' };
};
useServer(
{
schema,
context: wsContext,
}
wsServer,
);
You could use it like so in your Apollo React client:
import { GraphQLWsLink } from '#apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
const wsLink = new GraphQLWsLink(createClient({
url: 'ws://localhost:4000/subscriptions',
connectionParams: {
authorization: user.authToken,
},
}));

Resources