import { PubSubAsyncIterator } from './pubsub-async-iterator' ; import { PubSubEngine } from 'graphql-subscriptions' ; import * as nats from 'nats' ; export class NatsPubSub implements PubSubEngine { private nats : nats . Client ; constructor ( options ) { if ( options . nc ) { this . nats = options . nc ; } else { this . nats = nats . connect ( options ) ; } } public async publish ( subject , payload ) { return await this . nats . publish ( subject , JSON . stringify ( payload ) ) ; } public async subscribe ( subject , onMessage ) { return await this . nats . subscribe ( subject , ( event ) => onMessage ( JSON . parse ( event ) ) ) ; } public unsubscribe ( sid ) { this . nats . unsubscribe ( sid ) ; } public asyncIterator < T > ( subjects ) { return new PubSubAsyncIterator < T > ( this , subjects ) ; } }