DaSch
DaSch

Reputation: 941

How to use Ix AsyncIterator for nest.js GraphQL Subscription

I have a special use case where I wanted to use GraphQL as a proxy for an existing WebSocket Server. But somehow I don't get the subscriptions to work at all.

As I can't use the PubSub stuff that is shipped with NestJS I came to the conclusion that it would be the easiest to use Ix to create an AsyncIterator. To have a prove of concept that it works at all I reduced my code done to this:

@Resolver((of) => –)
export class TestResolver {
  constructor() {}


  @Subscription((returns) => Number)
  counter(): AsyncIterator<number> {
    return from([1, 2, 3, 4, 5, 6])[Symbol.asyncIterator]();
  }
}


Which at least should return 6 or something. But my client complains with 'Cannot return null for non-nullable field Subscription.counter.'

I have now idea what could be wrong with this code and why this may return null.

––––

I also tried with an AsyncIterator without Ix which might produce a little bit nicer output but actually also fails with the same error.

async function* generateSequence(start, end) {
  for (let i = start; i <= end; i++) {
    // Wow, can use await!
    await new Promise((resolve) => setTimeout(resolve, 1000));

    yield i;
  }
}


@Resolver((of) => –)
export class TestResolver {
  constructor() {}


  @Subscription((returns) => Number)
  counter(): AsyncIterator<number> {
    return generateSequence(1, 100);
  }
}


Upvotes: 1

Views: 413

Answers (0)

Related Questions