typescriptrxjsgraphqlprismaasync-iterator

How to use a prisma graphql subscription in node app


I am following this guide. I am trying to listen to a graphQL subscription in my node app. I am having a lot of trouble implementing that subscription. I have a tried a few different ways, listed below, none of them are working.

// converted to rxjs observables
from(PrismaClient.$subscribe.priority({
    mutation_in: "CREATED"
})).subscribe(
    (next) => {
        console.log("next", next);
    },
    () => {
        console.log("error");
    },
    () => {
        console.log("complete");
    }
);

// as promise
PrismaClient.$subscribe.priority({
    mutation_in: "CREATED"
}).then(
    (next) => {
        console.log("next", next);
    }
);

Both of these just return in the next:

{ next: [Function: next],
  return: [Function: return],
  throw: [Function: throw],
  '@@asyncIterator': [Function] }

I would expect it to return the priority that was created any time a new one is created. However, it only returns one time and immediately completes and returns that object i listed above.

I understand this has something to do with it returning back an Promise<AsyncIterator<...>>, but i am not sure how to solve this issue.

How do i create a prisma graphql subscription in a node app using the prisma-client? I would also, like to convert this to rxjs instead of using promises. I just prefer Observables.


Solution

  • Here's a suggestion with Promises and async/await:

    const main = async () => {
      const subscription = await PrismaClient.$subscribe.priority({
        mutation_in: 'CREATED',
      })
      handleSubscription(subscription)
    }
    
    const handleSubscription = async (subscription) => {
      const result = await subscription.next()
      console.log('do stuff with', result.value)
    
      if (!result.done) {
        console.log('handle again')
        handleSubscription(subscription)
      }
      else {
        console.log('done')
      }
    }
    
    main().catch(e => console.error(e))