Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass koa context to graphql? #1392

Closed
Stolenko opened this issue Jul 22, 2018 · 2 comments
Closed

How to pass koa context to graphql? #1392

Stolenko opened this issue Jul 22, 2018 · 2 comments

Comments

@Stolenko
Copy link

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
@Louis-T
Copy link

Louis-T commented Jul 23, 2018

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

@martijnwalraven
Copy link
Contributor

It seems this has been resolved.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants