{"_id":"@carlevans719/graphql-redis-subscriptions","name":"@carlevans719/graphql-redis-subscriptions","dist-tags":{"latest":"2.4.3"},"versions":{"2.4.3":{"name":"@carlevans719/graphql-redis-subscriptions","version":"2.4.3","description":"A graphql-subscriptions PubSub Engine using redis","main":"dist/index.js","repository":{"type":"git","url":"https://github.com/davidyaha/graphql-redis-subscriptions.git"},"keywords":["graphql","redis","apollo","subscriptions"],"author":{"name":"David Yahalomi"},"contributors":[{"name":"Michał Lytek","url":"https://github.com/19majkel94"}],"license":"MIT","bugs":{"url":"https://github.com/davidyaha/graphql-redis-subscriptions/issues"},"homepage":"https://github.com/davidyaha/graphql-redis-subscriptions","scripts":{"compile":"tsc","test":"npm run coverage && npm run lint","lint":"eslint src --ext ts","watch":"tsc -w","testonly":"mocha --reporter spec src/test/tests.ts","integration":"mocha --reporter spec src/test/integration-tests.ts","coverage":"nyc --reporter=html --reporter=text mocha src/test/**/*.ts","prepublish":"tsc"},"dependencies":{"iterall":"^1.3.0"},"peerDependencies":{"graphql-subscriptions":"^1.0.0 || ^2.0.0"},"devDependencies":{"@istanbuljs/nyc-config-typescript":"^1.0.1","@types/chai":"^4.2.12","@types/chai-as-promised":"^7.1.3","@types/ioredis":"^4.17.3","@types/mocha":"^8.0.3","@types/node":"16.11.7","@types/simple-mock":"^0.8.1","@typescript-eslint/eslint-plugin":"^4.0.0","@typescript-eslint/parser":"^3.10.1","chai":"^4.2.0","chai-as-promised":"^7.1.1","eslint":"^7.7.0","graphql":"^15.7.2","graphql-subscriptions":"^2.0.0","mocha":"^8.1.3","nyc":"^15.1.0","simple-mock":"^0.8.0","ts-node":"^10.4.0","typescript":"^4.0.2"},"optionalDependencies":{"ioredis":"^4.17.3"},"typings":"dist/index.d.ts","typescript":{"definition":"dist/index.d.ts"},"licenseText":"MIT License\n\nCopyright (c) 2016 David Yahalomi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","_id":"@carlevans719/graphql-redis-subscriptions@2.4.3","dist":{"shasum":"85ac1178cb15720a2945fbc2697ebc38dc37b595","integrity":"sha512-pE2hZ++mNpMe6Yr5pbwqpaFPqBopcujLA+Fy75vC6zp13Y1jawcg9A5QtvOf0IotMTDciVw+zBXqaXdc+49QMQ==","tarball":"https://registry.npmjs.org/@carlevans719/graphql-redis-subscriptions/-/graphql-redis-subscriptions-2.4.3.tgz","fileCount":43,"unpackedSize":234906,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDj8nKKwabwfFKCjYNeby/pvJuFMZ5G52GJlOCs2aBDYgIhAIuT38yl4+jERAuOEag6oqCc4i/rPtTNn7WN3RoBh7Mb"}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJihQUtACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqMIBAAjvLfgKKIc5lOjykUzRwZw5EDeXtWFmzpKLIrj6Df75NoIIbN\r\nj684CQasqs0Y+V6vH2ZvMGJCnoODLcYJJm2JYx3oxlRzDXo2x363/0oeIs1j\r\n93XLks9VkXHjmHAFoCoK04r3sdgbzKGBcExamG1yqkLtEqHTcOIgVvTQbLvV\r\nvmjFKmBEFNj/EI4BGJlZl0Iftec0CzKrQVI3wv2sRafAnM/Rg+yXuSD8eiZk\r\nVDUpyGc4piZuKcYS10T8jo9VM+c/pQcl6G3WvxE8kzrdikzQW3iJYklQQlN6\r\nLAvy1eUOZC/HrotFPwBTywf7yRDAbUuVRYXLmpz/YNK5HGgEJfl76Hh2c4OE\r\n+EodRCAXIkq9p9spDeF+z2QKyXDRr9MeV9NvEvz1K5433Pq3rp0TOyAj68JA\r\nBuTt2GuTRZi0Ed5xJOk5kz9U44vFc9iMCkE4UmSr89S+AzaKdEXMoxGtlL9M\r\nEqYOd0e5P7Xvdk7solB1GYDOiLIbLccX5sTJwxLuU6kNG0GPKFfBZ+MWDp1v\r\nUSFU355fEO1w1GHeUmu/Ly3LTyOFcByTio3kx9K9Y7XfVwCE4Ji5w1p0UNZu\r\nBj63AwtlgNpZmlxpNAuCru1F6NYT7FShLzh+/rPMi9tFKoPYABdV438nUixI\r\n0dJANUl2uUbViqAAkmsBI3FtZupIupXZGEE=\r\n=xMKH\r\n-----END PGP SIGNATURE-----\r\n"},"_npmUser":{"name":"carlevans719","email":"carlevans719691@gmail.com"},"directories":{},"maintainers":[{"name":"carlevans719","email":"carlevans719691@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/graphql-redis-subscriptions_2.4.3_1652884781743_0.24676615395445878"},"_hasShrinkwrap":false}},"time":{"created":"2022-05-18T14:39:41.741Z","2.4.3":"2022-05-18T14:39:41.950Z","modified":"2022-05-18T14:39:42.189Z"},"maintainers":[{"name":"carlevans719","email":"carlevans719691@gmail.com"}],"description":"A graphql-subscriptions PubSub Engine using redis","homepage":"https://github.com/davidyaha/graphql-redis-subscriptions","keywords":["graphql","redis","apollo","subscriptions"],"repository":{"type":"git","url":"https://github.com/davidyaha/graphql-redis-subscriptions.git"},"contributors":[{"name":"Michał Lytek","url":"https://github.com/19majkel94"}],"author":{"name":"David Yahalomi"},"bugs":{"url":"https://github.com/davidyaha/graphql-redis-subscriptions/issues"},"license":"MIT","readme":"# graphql-redis-subscriptions\n\n[![Dependabot badge](https://flat.badgen.net/dependabot/davidyaha/graphql-redis-subscriptions?icon=dependabot)](https://dependabot.com/)\n[![Build Status](https://travis-ci.org/davidyaha/graphql-redis-subscriptions.svg?branch=master)](https://travis-ci.org/davidyaha/graphql-redis-subscriptions)\n\nThis package implements the PubSubEngine Interface from the [graphql-subscriptions](https://github.com/apollographql/graphql-subscriptions) package and also the new AsyncIterator interface. \nIt allows you to connect your subscriptions manager to a Redis Pub Sub mechanism to support \nmultiple subscription manager instances.\n\n## Installation\nAt first, install the `graphql-redis-subscriptions` package: \n```\nnpm install graphql-redis-subscriptions\n```\n\nAs the [graphql-subscriptions](https://github.com/apollographql/graphql-subscriptions) package is declared as a peer dependency, you might receive warning about an unmet peer dependency if it's not installed already by one of your other packages. In that case you also need to install it too:\n```\nnpm install graphql-subscriptions\n```\n   \n## Using as AsyncIterator\n\nDefine your GraphQL schema with a `Subscription` type:\n\n```graphql\nschema {\n  query: Query\n  mutation: Mutation\n  subscription: Subscription\n}\n\ntype Subscription {\n    somethingChanged: Result\n}\n\ntype Result {\n    id: String\n}\n```\n\nNow, let's create a simple `RedisPubSub` instance:\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\nconst pubsub = new RedisPubSub();\n```\n\nNow, implement your Subscriptions type resolver, using the `pubsub.asyncIterator` to map the event you need:\n\n```javascript\nconst SOMETHING_CHANGED_TOPIC = 'something_changed';\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: () => pubsub.asyncIterator(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\nCalling the method `asyncIterator` of the `RedisPubSub` instance will send redis a `SUBSCRIBE` message to the topic provided and will return an `AsyncIterator` binded to the RedisPubSub instance and listens to any event published on that topic.\nNow, the GraphQL engine knows that `somethingChanged` is a subscription, and every time we will use `pubsub.publish` over this topic, the `RedisPubSub` will `PUBLISH` the event over redis to all other subscribed instances and those in their turn will emit the event to GraphQL using the `next` callback given by the GraphQL engine.\n\n```js\npubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: \"123\" }});\n```\n\n## Dynamically create a topic based on subscription args passed on the query\n\n```javascript\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),\n    },\n  },\n}\n```\n\n## Using a pattern on subscription\n\n```javascript\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}.*`, { pattern: true })\n    },\n  },\n}\n```\n\n## Using both arguments and payload to filter events\n\n```javascript\nimport { withFilter } from 'graphql-subscriptions';\n\nexport const resolvers = {\n  Subscription: {\n    somethingChanged: {\n      subscribe: withFilter(\n        (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),\n        (payload, variables) => payload.somethingChanged.id === variables.relevantId,\n      ),\n    },\n  },\n}\n```\n\n## Creating the Redis Client\n\nThe basic usage is great for development and you will be able to connect to a Redis server running on your system seamlessly. For production usage, it is recommended to pass a redis client (like ioredis) to the RedisPubSub constructor. This way you can control all the options of your redis connection, for example the connection retry strategy.\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\nimport * as Redis from 'ioredis';\n\nconst options = {\n  host: REDIS_DOMAIN_NAME,\n  port: PORT_NUMBER,\n  retryStrategy: times => {\n    // reconnect after\n    return Math.min(times * 50, 2000);\n  }\n};\n\nconst pubsub = new RedisPubSub({\n  ...,\n  publisher: new Redis(options),\n  subscriber: new Redis(options)\n});\n```\n\n**Receiving messages as Buffers**\n\nSome Redis use cases require receiving binary-safe data back from redis (in a Buffer). To accomplish this, override the event names for receiving messages and pmessages.  Different redis clients use different names, for example:\n\n| library | message event | message event (Buffer) | pmessage event | pmessage event (Buffer) |\n| ------- | ------------- | ---------------------- | -------------- | ----------------------- |\n| ioredis | `message` | `messageBuffer` | `pmessage` | `pmessageBuffer` |\n| node-redis | `message` | `message_buffer` | `pmessage` | `pmessage_buffer` |\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\nimport * as Redis from 'ioredis';\n\nconst pubsub = new RedisPubSub({\n  ...,\n  // Tells RedisPubSub to register callbacks on the messageBuffer and pmessageBuffer EventEmitters\n  messageEventName: 'messageBuffer',\n  pmessageEventName: 'pmessageBuffer',\n});\n```\n\n\n**Also works with your Redis Cluster**\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\nimport { Cluster } from 'ioredis';\n\nconst cluster = new Cluster(REDIS_NODES); // like: [{host: 'ipOrHost', port: 1234}, ...]\nconst pubsub = new RedisPubSub({\n  ...,\n  publisher: cluster,\n  subscriber: cluster\n});\n```\n\n\nYou can learn more on the `ioredis` package [here](https://github.com/luin/ioredis).\n\n## Using a custom reviver\n\nBy default, Javascript objects are serialized using the `JSON.stringify` and `JSON.parse` methods.\nThis means that not all objects - such as Date or Regexp objects - will deserialize correctly without a custom reviver, that work out of the box with the default in-memory implementation.\nFor handling such objects, you may pass your own reviver function to `JSON.parse`, for example to handle Date objects the following reviver can be used:\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\n\nconst dateReviver = (key, value) => {\n  const isISO8601Z = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/;\n  if (typeof value === 'string' && isISO8601Z.test(value)) {\n    const tempDateNumber = Date.parse(value);\n    if (!isNaN(tempDateNumber)) {\n      return new Date(tempDateNumber);\n    }\n  }\n  return value;\n};\n\nconst pubSub = new RedisPubSub({ ..., reviver: dateReviver });\n\npubSub.publish('Test', {\n  validTime: new Date(),\n  invalidTime: '2018-13-01T12:00:00Z'\n});\npubSub.subscribe('Test', message => {\n  message.validTime; // Javascript Date\n  message.invalidTime; // string\n});\n```\n\n## Old Usage (Deprecated)\n\n```javascript\nimport { RedisPubSub } from 'graphql-redis-subscriptions';\nconst pubsub = new RedisPubSub();\nconst subscriptionManager = new SubscriptionManager({\n  schema,\n  pubsub,\n  setupFunctions: {},\n});\n```\n\n## Using Trigger Transform (Deprecated)\n\nRecently, graphql-subscriptions package added a way to pass in options to each call of subscribe.\nThose options are constructed via the setupFunctions object you provide the Subscription Manager constructor.\nThe reason for graphql-subscriptions to add that feature is to allow pub sub engines a way to reduce their subscription set using the best method of said engine.\nFor example, Meteor's live query could use Mongo selector with arguments passed from the subscription like the subscribed entity id.\nFor Redis, this could be a bit more simplified, but much more generic.\nThe standard for Redis subscriptions is to use dot notations to make the subscription more specific.\nThis is only the standard but I would like to present an example of creating a specific subscription using the channel options feature.\n\nFirst I create a simple and generic trigger transform \n```javascript\nconst triggerTransform = (trigger, {path}) => [trigger, ...path].join('.');\n```\n\nThen I pass it to the `RedisPubSub` constructor.\n```javascript\nconst pubsub = new RedisPubSub({\n  triggerTransform,\n});\n```\nLastly, I provide a setupFunction for `commentsAdded` subscription field.\nIt specifies one trigger called `comments.added` and it is called with the channelOptions object that holds `repoName` path fragment.\n```javascript\nconst subscriptionManager = new SubscriptionManager({\n  schema,\n  setupFunctions: {\n    commentsAdded: (options, {repoName}) => ({\n      'comments.added': {\n        channelOptions: {path: [repoName]},\n      },\n    }),\n  },\n  pubsub,\n});\n```\n\nWhen I call `subscribe` like this:\n```javascript\nconst query = `\n  subscription X($repoName: String!) {\n    commentsAdded(repoName: $repoName)\n  }\n`;\nconst variables = {repoName: 'graphql-redis-subscriptions'};\nsubscriptionManager.subscribe({query, operationName: 'X', variables, callback});\n```\n\nThe subscription string that Redis will receive will be `comments.added.graphql-redis-subscriptions`.\nThis subscription string is much more specific and means the the filtering required for this type of subscription is not needed anymore.\nThis is one step towards lifting the load off of the GraphQL API server regarding subscriptions.\n\n## Tests\n\n### Spin a Redis in docker server and cluster\nPlease refer to https://github.com/Grokzen/docker-redis-cluster documentation to start a cluster\n```shell script\n$ docker run --rm -p 6379:6379 redis:alpine\n$ export REDIS_CLUSTER_IP=0.0.0.0; docker run -e \"IP=0.0.0.0\" --rm -p 7006:7000 -p 7001:7001 -p 7002:7002 -p 7003:7003 -p 7004:7004 -p 7005:7005 grokzen/redis-cluster\n```\n\n### Test\n```shell script\nnpm run test\n```\n","readmeFilename":"README.md"}