Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass request body into GraphQL Context?

I'm currently attempting to get the request body into context, because part of the body contains a JWT that needs to be decoded. However when I try the following I get undefined for context:

    app.use('/', graphqlHTTP((req) => ({
      schema: Schema,
      context: req.body,
      pretty: true,
      graphiql: false
    })));

I logged out req and I didn't see body in there. I'm using a library called react-reach, it adds the following to the body on the request:

    {
      query: {...},
      queryParams: {...},
      options: {
       token: '...' // <-- I'm passing the token into options
      }
    }

I know the body is being interpreted because my queries/mutations that are in the body are being interpreted and executed. Just can't seem to find it when passed to context.

like image 382
kennet postigo Avatar asked May 19 '16 18:05

kennet postigo


People also ask

How do I send a request in GraphQL?

GraphQL requests can be sent via HTTP POST or HTTP GET requests. GET requests must be sent in the following format. The query, variables, and operation are sent as URL-encoded query parameters in the URL. In either request method (POST or GET), only query is required.

How do you pass an object to a GraphQL query?

const filterType = new GraphQLObjectType ({ name: 'filterType', fields: { fieldName: { type: GraphQLString }, fieldValues: { type: GraphQLString }, filterType: { type: GraphQLString }, } }) const QueryType = new GraphQLObjectType({ name: 'Query', fields: () => ({ accounts: { type: new GraphQLList(accountType), args: { ...

How do you use context in GraphQL?

In GraphQL, a context is an object shared by all the resolvers of a specific execution. It's useful for keeping data such as authentication info, the current user, database connection, data sources and other things you need for running your business logic.


1 Answers

Your req.body is undefined unless you're using additional body-parser middleware. From the Express documentation:

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer. http://expressjs.com/en/api.html#req.body

graphqlHTTP is doing it's own thing to parse the request body (see here) and that's why your queries/mutations are working.

Adding middleware (like body-parser or multer) to parse the request body should make it available on req.body and then your context should become populated with what you're looking for.

like image 144
Marco Lüthy Avatar answered Oct 05 '22 12:10

Marco Lüthy