How to extend the context object of a graphql call?

Member

by dedrick , in category: Javascript , a month ago

How to extend the context object of a graphql call?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 10 days ago

@dedrick 

To extend the context object of a GraphQL call, you can do the following:

  1. Define a custom context interface: First, create a custom interface that extends the default context object provided by your GraphQL server. This interface will include any additional properties or methods you want to add to the context object.
1
2
3
4
interface CustomContext extends Context {
  // Add custom properties or methods here
  user: User;
}


  1. Update your GraphQL server configuration: Modify your GraphQL server configuration to include the custom context interface. This can typically be done in the server setup code where you define your GraphQL schema and context.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: ({ req }): CustomContext => {
    // Access the default context object
    const defaultContext = createContext(req);

    // Extend the default context with custom properties or methods
    const customContext: CustomContext = {
      ...defaultContext,
      user: getUserFromRequest(req)
    };

    return customContext;
  }
});


  1. Access the extended context in GraphQL resolvers: Once you have extended the context object, you can access the custom properties or methods in your GraphQL resolvers.
1
2
3
4
5
6
7
const resolvers = {
  Query: {
    currentUser: (_, __, { user }: CustomContext) => {
      return user;
    },
  },
};


By following these steps, you can extend the context object of a GraphQL call with custom properties or methods to provide additional functionality or data to your resolvers.