Apollo-server: How to pass koa context to graphql?

Created on 22 Jul 2018  路  2Comments  路  Source: apollographql/apollo-server

Hello, I use koa and koa-passport for authorization via steam.
But koa and graphql have different contexts.

How to pass koa context to graphql?

router.get('/', (ctx) => {
  console.log(ctx.state);
  ctx.body = ''
})

in console:

{ _passport:
   { instance:
      Authenticator {
        _key: 'passport',
        _strategies: [Object],
        _serializers: [Array],
        _deserializers: [Array],
        _infoTransformers: [],
        _framework: [Object],
        _userProperty: 'user',
        _sm: [SessionManager],
        Authenticator: [Function: Authenticator],
        Passport: [Function: Authenticator],
        Strategy: [Function],
        strategies: [Object],
        KoaPassport: [Function: KoaPassport] },
     session: { user: [Object] } },
  user:
   { steamid: '76561198002188570',
     name: 'Stolen',
     avatar:
      'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/10/10986ae508588c55768d9d68697cb1391e398537.jpg' } }

Apollo server:

const apollo = new ApolloServer({
  schema,
  context: ({ ctx }) => ({ ctx })
})

...

apollo.applyMiddleware({ app })

my test resolver:

  Query: {
    test: (parent, args, ctx, info) => {
      console.log(ctx.state);
      return "testsQ"
    }
  }

in console:

undefined

Most helpful comment

Hi,

In the ApolloServer context method (context: ({ ctx }) => ({ ctx })), you are returning an object which contains a ctx key, with the koa context as value.

Then, in your resolver, you try to access ctx.state, but ctx here is an object (see above), and not the koa context.

So, either you access the context in the resolver this way :

 Query: {
    test: (parent, args, ctx, info) => {
      console.log(ctx.ctx.state);
      return "testsQ"
    }
  }

Or you return directly the koa context in the ApolloServer context method : context: ({ ctx }) => ctx

Bye

All 2 comments

Hi,

In the ApolloServer context method (context: ({ ctx }) => ({ ctx })), you are returning an object which contains a ctx key, with the koa context as value.

Then, in your resolver, you try to access ctx.state, but ctx here is an object (see above), and not the koa context.

So, either you access the context in the resolver this way :

 Query: {
    test: (parent, args, ctx, info) => {
      console.log(ctx.ctx.state);
      return "testsQ"
    }
  }

Or you return directly the koa context in the ApolloServer context method : context: ({ ctx }) => ctx

Bye

It seems this has been resolved.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

veeramarni picture veeramarni  路  3Comments

attdona picture attdona  路  3Comments

dbrrt picture dbrrt  路  3Comments

dobesv picture dobesv  路  3Comments

nevyn-lookback picture nevyn-lookback  路  3Comments