{"name":"graphql-subscriptions","version":"3.0.0","description":"GraphQL subscriptions for node.js","main":"dist/index.js","repository":{"type":"git","url":"git+https://github.com/apollographql/graphql-subscriptions.git"},"dependencies":{},"peerDependencies":{"graphql":"^15.7.2 || ^16.0.0"},"scripts":{"clean":"rimraf dist coverage","compile":"tsc","pretest":"npm run compile","test":"npm run testonly --","posttest":"npm run lint","lint":"tslint --project ./tsconfig.json ./src/**/*.ts","watch":"tsc -w","testonly":"node --expose-gc ./node_modules/.bin/mocha --reporter spec --full-trace ./dist/test/tests.js ./dist/test/asyncIteratorSubscription.js","coverage":"node --expose-gc ./node_modules/istanbul/lib/cli.js cover _mocha -- --full-trace ./dist/test/tests.js ./dist/test/asyncIteratorSubscription.js","postcoverage":"remap-istanbul --input coverage/coverage.raw.json --type lcovonly --output coverage/lcov.info","prepare":"npm run clean && npm run compile"},"devDependencies":{"@types/chai-as-promised":"^7.1.4","@types/graphql":"^14.5.0","@types/mocha":"^9.0.0","@types/node":"^16.11.9","@types/sinon":"10.0.6","@types/sinon-chai":"^3.2.5","chai":"^4.3.4","chai-as-promised":"^7.1.1","graphql":"^16.0.0","istanbul":"^1.1.0-alpha.1","mocha":"^9.1.3","remap-istanbul":"^0.13.0","rimraf":"^3.0.2","sinon":"^12.0.1","sinon-chai":"^3.7.0","tslint":"^6.1.2","typescript":"^4.5.2"},"typings":"dist/index.d.ts","typescript":{"definition":"dist/index.d.ts"},"license":"MIT","_id":"graphql-subscriptions@3.0.0","contributors":[{"name":"Authors"},{"name":"Jonas Helfer","email":"helfer@users.noreply.github.com"},{"name":"Jonas Helfer","email":"jonas@helfer.email"},{"name":"Quint Stoffers","email":"quintstoffers@users.noreply.github.com"},{"name":"Sashko Stubailo","email":"s.stubailo@gmail.com"},{"name":"Sashko Stubailo","email":"sashko@stubailo.com"},{"name":"David Yahalomi","email":"davidyaha@users.noreply.github.com"},{"name":"Alexander Anich","email":"Anichale@users.noreply.github.com"},{"name":"Francois Valdy","email":"gluck@users.noreply.github.com"},{"name":"Daniel Rinehart","email":"NeoPhi@users.noreply.github.com"}],"gitHead":"d74107ce9dbc11d46eba0e20efa61bda140068de","bugs":{"url":"https://github.com/apollographql/graphql-subscriptions/issues"},"homepage":"https://github.com/apollographql/graphql-subscriptions#readme","_nodeVersion":"18.19.0","_npmVersion":"10.2.3","dist":{"integrity":"sha512-kZCdevgmzDjGAOqH7GlDmQXYAkuHoKpMlJrqF40HMPhUhM5ZWSFSxCwD/nSi6AkaijmMfsFhoJRGJ27UseCvRA==","shasum":"820c846ef271414c08f64827b5c9a192801e1b6f","tarball":"http://registry-npm.ywwl.com/graphql-subscriptions/download/graphql-subscriptions-3.0.0.tgz","fileCount":27,"unpackedSize":61019,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIEzCaoeJnoqJOZXGhVx7qM57HUGxezZMFz65sWxBssqFAiEAuyAizxmeYHG0l05SnyqbiJTrYbx1AT8rrVzrxe1gA00="}],"size":18567,"noattachment":false,"key":"/graphql-subscriptions/-/graphql-subscriptions-3.0.0.tgz"},"_npmUser":{"name":"apollo-bot","email":"npm@apollographql.com"},"directories":{},"maintainers":[{"name":"apollo-bot","email":"npm@apollographql.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/graphql-subscriptions_3.0.0_1731361643110_0.5648639081911517"},"_hasShrinkwrap":false,"readme":"[![npm version](https://badge.fury.io/js/graphql-subscriptions.svg)](https://badge.fury.io/js/graphql-subscriptions) [![GitHub license](https://img.shields.io/github/license/apollostack/graphql-subscriptions.svg)](https://github.com/apollographql/graphql-subscriptions/blob/master/LICENSE)\n\n# graphql-subscriptions\n\nGraphQL subscriptions is a simple npm package that lets you wire up GraphQL with a pubsub system (like Redis) to implement subscriptions in GraphQL.\n\nYou can use it with any GraphQL client and server (not only Apollo).\n\n### Installation\n\n`npm install graphql-subscriptions graphql` or `yarn add graphql-subscriptions graphql`\n\n> This package should be used with a network transport, for example [subscriptions-transport-ws](https://github.com/apollographql/subscriptions-transport-ws).\n\n### TypeScript\n\nIf you are developing a project that uses this module with TypeScript:\n\n- ensure that your `tsconfig.json` `lib` definition includes `\"es2018.asynciterable\"`\n- `npm install @types/graphql` or `yarn add @types/graphql`\n\n### Getting started with your first subscription\n\nTo begin with GraphQL subscriptions, start by defining a GraphQL `Subscription` type in your schema:\n\n```graphql\ntype Subscription {\n  somethingChanged: Result\n}\n\ntype Result {\n  id: String\n}\n```\n\nNext, add the `Subscription` type to your `schema` definition:\n\n```graphql\nschema {\n  query: Query\n  mutation: Mutation\n  subscription: Subscription\n}\n```\n\nNow, let's create a simple `PubSub` instance - it is a simple pubsub implementation, based on `EventEmitter`. Alternative `EventEmitter` implementations can be passed by an options object\nto the `PubSub` constructor.\n\n```js\nimport { PubSub } from \"graphql-subscriptions\";\n\nexport const pubsub = new PubSub();\n```\n\nIf you're using TypeScript you can use the optional generic parameter for added type-safety:\n\n```ts\nimport { PubSub } from \"graphql-subscriptions\";\n\nconst pubsub = new PubSub<{\n  EVENT_ONE: { data: number };\n  EVENT_TWO: { data: string };\n}>();\n\npubsub.publish(\"EVENT_ONE\", { data: 42 });\npubsub.publish(\"EVENTONE\", { data: 42 }); // ! ERROR\npubsub.publish(\"EVENT_ONE\", { data: \"42\" }); // ! ERROR\npubsub.publish(\"EVENT_TWO\", { data: \"hello\" });\n\npubsub.subscribe(\"EVENT_ONE\", () => {});\npubsub.subscribe(\"EVENTONE\", () => {}); // ! ERROR\npubsub.subscribe(\"EVENT_TWO\", () => {});\n```\n\nNext implement your Subscriptions type resolver using the `pubsub.asyncIterableIterator` to map the event you need:\n\n```js\nconst SOMETHING_CHANGED_TOPIC = \"something_changed\";\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: () => pubsub.asyncIterableIterator(SOMETHING_CHANGED_TOPIC),\n    },\n  },\n};\n```\n\n> Subscriptions resolvers are not a function, but an object with `subscribe` method, that returns `AsyncIterable`.\n\nThe GraphQL engine now knows that `somethingChanged` is a subscription, and every time we use `pubsub.publish` it will publish content using our chosen transport layer:\n\n```js\npubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: \"123\" } });\n```\n\n> Note that the default PubSub implementation is intended for demo purposes. It only works if you have a single instance of your server and doesn't scale beyond a couple of connections.\n> For production usage you'll want to use one of the [PubSub implementations](#pubsub-implementations) backed by an external store. (e.g. Redis)\n\n### Filters\n\nWhen publishing data to subscribers, we need to make sure that each subscriber gets only the data it needs.\n\nTo do so, we can use `withFilter` helper from this package, which wraps `AsyncIterator` with a filter function, and lets you control each publication for each user.\n\n`withFilter` API:\n\n- `asyncIteratorFn: (rootValue, args, context, info) => AsyncIterator<any>` : A function that returns `AsyncIterator` you got from your `pubsub.asyncIterableIterator`.\n- `filterFn: (payload, variables, context, info) => boolean | Promise<boolean>` - A filter function, executed with the payload (the published value), variables, context and operation info, must return `boolean` or `Promise<boolean>` indicating if the payload should pass to the subscriber.\n\nFor example, if `somethingChanged` would also accept a variable with the ID that is relevant, we can use the following code to filter according to it:\n\n```js\nimport { withFilter } from \"graphql-subscriptions\";\n\nconst SOMETHING_CHANGED_TOPIC = \"something_changed\";\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: withFilter(\n        () => pubsub.asyncIterableIterator(SOMETHING_CHANGED_TOPIC),\n        (payload, variables) => {\n          return payload.somethingChanged.id === variables.relevantId;\n        }\n      ),\n    },\n  },\n};\n```\n\n> Note that when using `withFilter`, you don't need to wrap your return value with a function.\n\n### Channels Mapping\n\nYou can map multiple channels into the same subscription, for example when there are multiple events that trigger the same subscription in the GraphQL engine.\n\n```js\nconst SOMETHING_UPDATED = \"something_updated\";\nconst SOMETHING_CREATED = \"something_created\";\nconst SOMETHING_REMOVED = \"something_removed\";\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: () =>\n        pubsub.asyncIterableIterator([\n          SOMETHING_UPDATED,\n          SOMETHING_CREATED,\n          SOMETHING_REMOVED,\n        ]),\n    },\n  },\n};\n```\n\n### Payload Manipulation\n\nYou can also manipulate the published payload, by adding `resolve` methods to your subscription:\n\n```js\nconst SOMETHING_UPDATED = \"something_updated\";\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      resolve: (payload, args, context, info) => {\n        // Manipulate and return the new value\n        return payload.somethingChanged;\n      },\n      subscribe: () => pubsub.asyncIterableIterator(SOMETHING_UPDATED),\n    },\n  },\n};\n```\n\nNote that `resolve` methods execute _after_ `subscribe`, so if the code in `subscribe` depends on a manipulated payload field, you will need to factor out the manipulation and call it from both `subscribe` and `resolve`.\n\n### Usage with callback listeners\n\nYour database might have callback-based listeners for changes, for example something like this:\n\n```js\nconst listenToNewMessages = (callback) => {\n  return db.table(\"messages\").listen((newMessage) => callback(newMessage));\n};\n\n// Kick off the listener\nlistenToNewMessages((message) => {\n  console.log(message);\n});\n```\n\nThe `callback` function would be called every time a new message is saved in the database. Unfortunately, that doesn't play very well with async iterators out of the box because callbacks are push-based, where async iterators are pull-based.\n\nWe recommend using the [`callback-to-async-iterator`](https://github.com/withspectrum/callback-to-async-iterator) module to convert your callback-based listener into an async iterator:\n\n```js\nimport asyncify from \"callback-to-async-iterator\";\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: () => asyncify(listenToNewMessages),\n    },\n  },\n};\n```\n\n### Custom `AsyncIterator` Wrappers\n\nThe value you should return from your `subscribe` resolver must be an `AsyncIterable`.\n\nYou can wrap an `AsyncIterator` with custom logic for your subscriptions. For compatibility with APIs that require `AsyncIterator` or `AsyncIterable`, your wrapper can return an `AsyncIterableIterator` to comply with both.\n\nFor example, the following implementation manipulates the payload by adding some static fields:\n\n```typescript\nexport const withStaticFields = (\n  asyncIterator: AsyncIterator<any>,\n  staticFields: Object\n): Function => {\n  return (\n    rootValue: any,\n    args: any,\n    context: any,\n    info: any\n  ): AsyncIterableIterator<any> => {\n    return {\n      next() {\n        return asyncIterator.next().then(({ value, done }) => {\n          return {\n            value: {\n              ...value,\n              ...staticFields,\n            },\n            done,\n          };\n        });\n      },\n      return() {\n        return Promise.resolve({ value: undefined, done: true });\n      },\n      throw(error) {\n        return Promise.reject(error);\n      },\n      [Symbol.asyncIterator]() {\n        return this;\n      },\n    };\n  };\n};\n```\n\n> You can also take a look at `withFilter` for inspiration.\n\n### PubSub Implementations\n\nIt can be easily replaced with some other implementations of [PubSubEngine abstract class](https://github.com/apollographql/graphql-subscriptions/blob/master/src/pubsub-engine.ts). Here are a few of them:\n\n- Use Redis with https://github.com/davidyaha/graphql-redis-subscriptions\n- Use Google PubSub with https://github.com/axelspringer/graphql-google-pubsub\n- Use MQTT enabled broker with https://github.com/aerogear/graphql-mqtt-subscriptions\n- Use RabbitMQ with https://github.com/cdmbase/graphql-rabbitmq-subscriptions\n- Use AMQP (RabbitMQ) with https://github.com/Surnet/graphql-amqp-subscriptions\n- Use Kafka with https://github.com/ancashoria/graphql-kafka-subscriptions\n- Use Kafka (using [Kafkajs](https://www.npmjs.com/package/kafkajs)) with https://github.com/tomasAlabes/graphql-kafkajs-subscriptions\n- Use Postgres with https://github.com/GraphQLCollege/graphql-postgres-subscriptions\n- Use NATS with https://github.com/moonwalker/graphql-nats-subscriptions\n- Use Mongoose (MongoDB) with https://github.com/Nickolasmv/graphql-mongoose-subscriptions\n- Use multiple backends with https://github.com/jcoreio/graphql-multiplex-subscriptions\n- Use Ably for multi-protocol support with https://github.com/ably-labs/graphql-ably-pubsub\n- Use Google Firestore with https://github.com/m19c/graphql-firestore-subscriptions\n- Use Amazon's Simple Notification Service (SNS) and Simple Queue Service (SQS) with https://github.com/sagahead-io/graphql-snssqs-subscriptions\n- [Add your implementation...](https://github.com/apollographql/graphql-subscriptions/pull/new/master)\n\nYou can also implement a `PubSub` of your own, by using the exported abstract class `PubSubEngine` from this package. By using `extends PubSubEngine` you use the default `asyncIterator` method implementation; by using `implements PubSubEngine` you must implement your own `AsyncIterator`.\n\n#### SubscriptionManager **@deprecated**\n\n`SubscriptionManager` is the previous alternative for using `graphql-js` subscriptions directly, and it's now deprecated.\n\nIf you are looking for its API docs, refer to [a previous commit of the repository](https://github.com/apollographql/graphql-subscriptions/blob/5eaee92cd50060b3f3637f00c53960f51a07d0b2/README.md)\n","publish_time":1731361643279,"_cnpm_publish_time":1731361643279,"dist-tags":{"latest":"3.0.0"}}