Not able to get GraphQL subscriptions working with graphql codegen

I am currently trying to set up a subscription using graphql codegen types.

import { Context } from '../context'
import { SubscriptionResolvers } from '../../generated/graphql'

const NEW_POINT = 'NEW_POINT'

export const Subscription: SubscriptionResolvers = {
  scoreUpdated: {
    subscribe: (_parent, _args, context: Context) => {
      return context.pubsub.asyncIterator(NEW_POINT)
    },
  },
}

The error I’m getting when I hover over subscribe is:

Type '(_parent: {}, _args: {}, context: Context) => AsyncIterator<unknown, any, undefined>' is not assignable to type 'SubscriptionSubscribeFn<any, {}, any, {}>'.
  Type 'AsyncIterator<unknown, any, undefined>' is not assignable to type 'AsyncIterable<any> | Promise<AsyncIterable<any>>'.
    Type 'AsyncIterator<unknown, any, undefined>' is missing the following properties from type 'Promise<AsyncIterable<any>>': then, catch, finally, [Symbol.toStringTag]ts(2322)

I’m not sure what I’m missing to get this working. What am I missing?

1 Like

Im having the exact same issue with codegen… did you solve this?

The expected return type of subscribe is an AsyncIterable interface. I thought this was some crazy stuff, but for me this was enough to satisfy it:

     const asyncIterator = pubsub.asyncIterator(args)
      return {
        [Symbol.asyncIterator]() {
          return asyncIterator ;
        },
      };

This will however depend on the packages versions you are using. I’m personally using the latest versions of apollo-server, graphql-subscriptions, and ‘graphql-redis-subscriptions’

Did you guys solve this? I am also using codegen and ended up just typing it as any

I was able to get subscriptions to work by simply ignoring the error. I know that’s not the ideal solution but it was the only way I could find to get this to work.

Here is another solution which doesn’t require using @ts-ignore comments:

export const Subscription: SubscriptionResolvers = {
    scoreUpdated: {
      subscribe: (_parent, _args, context: Context) => {
        return {
          [Symbol.asyncIterator]: () => context.pubSub.asyncIterator(NEW_POINT),
        };
      },
    },
  },

Hi and thank you for the snippet, it works just fine!

Now my question is, how would you filter out events with the withFilter helper that’s described in the docs?

I’m trying to do it by the docs, but get this TS error:

Thank you