在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):davidyaha/graphql-redis-subscriptions开源软件地址(OpenSource Url):https://github.com/davidyaha/graphql-redis-subscriptions开源编程语言(OpenSource Language):TypeScript 99.3%开源软件介绍(OpenSource Introduction):graphql-redis-subscriptionsThis package implements the PubSubEngine Interface from the graphql-subscriptions package and also the new AsyncIterator interface. It allows you to connect your subscriptions manager to a Redis Pub Sub mechanism to support multiple subscription manager instances. InstallationAt first, install the
As the 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:
Using as AsyncIteratorDefine your GraphQL schema with a schema {
query: Query
mutation: Mutation
subscription: Subscription
}
type Subscription {
somethingChanged: Result
}
type Result {
id: String
} Now, let's create a simple import { RedisPubSub } from 'graphql-redis-subscriptions';
const pubsub = new RedisPubSub(); Now, implement your Subscriptions type resolver, using the const SOMETHING_CHANGED_TOPIC = 'something_changed';
export const resolvers = {
Subscription: {
somethingChanged: {
subscribe: () => pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC),
},
},
}
Calling the method pubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: "123" }}); Dynamically create a topic based on subscription args passed on the queryexport const resolvers = {
Subscription: {
somethingChanged: {
subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),
},
},
} Using a pattern on subscriptionexport const resolvers = {
Subscription: {
somethingChanged: {
subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}.*`, { pattern: true })
},
},
} Using both arguments and payload to filter eventsimport { withFilter } from 'graphql-subscriptions';
export const resolvers = {
Subscription: {
somethingChanged: {
subscribe: withFilter(
(_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),
(payload, variables) => payload.somethingChanged.id === variables.relevantId,
),
},
},
} Creating the Redis ClientThe 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. import { RedisPubSub } from 'graphql-redis-subscriptions';
import * as Redis from 'ioredis';
const options = {
host: REDIS_DOMAIN_NAME,
port: PORT_NUMBER,
retryStrategy: times => {
// reconnect after
return Math.min(times * 50, 2000);
}
};
const pubsub = new RedisPubSub({
...,
publisher: new Redis(options),
subscriber: new Redis(options)
}); Receiving messages as Buffers Some 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:
import { RedisPubSub } from 'graphql-redis-subscriptions';
import * as Redis from 'ioredis';
const pubsub = new RedisPubSub({
...,
// Tells RedisPubSub to register callbacks on the messageBuffer and pmessageBuffer EventEmitters
messageEventName: 'messageBuffer',
pmessageEventName: 'pmessageBuffer',
}); Also works with your Redis Cluster import { RedisPubSub } from 'graphql-redis-subscriptions';
import { Cluster } from 'ioredis';
const cluster = new Cluster(REDIS_NODES); // like: [{host: 'ipOrHost', port: 1234}, ...]
const pubsub = new RedisPubSub({
...,
publisher: cluster,
subscriber: cluster
}); You can learn more on the Using a custom reviverBy default, Javascript objects are serialized using the import { RedisPubSub } from 'graphql-redis-subscriptions';
const dateReviver = (key, value) => {
const isISO8601Z = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
if (typeof value === 'string' && isISO8601Z.test(value)) {
const tempDateNumber = Date.parse(value);
if (!isNaN(tempDateNumber)) {
return new Date(tempDateNumber);
}
}
return value;
};
const pubSub = new RedisPubSub({ ..., reviver: dateReviver });
pubSub.publish('Test', {
validTime: new Date(),
invalidTime: '2018-13-01T12:00:00Z'
});
pubSub.subscribe('Test', message => {
message.validTime; // Javascript Date
message.invalidTime; // string
}); Old Usage (Deprecated)import { RedisPubSub } from 'graphql-redis-subscriptions';
const pubsub = new RedisPubSub();
const subscriptionManager = new SubscriptionManager({
schema,
pubsub,
setupFunctions: {},
}); Using Trigger Transform (Deprecated)Recently, graphql-subscriptions package added a way to pass in options to each call of subscribe. Those options are constructed via the setupFunctions object you provide the Subscription Manager constructor. The 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. For example, Meteor's live query could use Mongo selector with arguments passed from the subscription like the subscribed entity id. For Redis, this could be a bit more simplified, but much more generic. The standard for Redis subscriptions is to use dot notations to make the subscription more specific. This is only the standard but I would like to present an example of creating a specific subscription using the channel options feature. First I create a simple and generic trigger transform const triggerTransform = (trigger, {path}) => [trigger, ...path].join('.'); Then I pass it to the const pubsub = new RedisPubSub({
triggerTransform,
}); Lastly, I provide a setupFunction for const subscriptionManager = new SubscriptionManager({
schema,
setupFunctions: {
commentsAdded: (options, {repoName}) => ({
'comments.added': {
channelOptions: {path: [repoName]},
},
}),
},
pubsub,
}); When I call const query = `
subscription X($repoName: String!) {
commentsAdded(repoName: $repoName)
}
`;
const variables = {repoName: 'graphql-redis-subscriptions'};
subscriptionManager.subscribe({query, operationName: 'X', variables, callback}); The subscription string that Redis will receive will be TestsSpin a Redis in docker server and clusterPlease refer to https://github.com/Grokzen/docker-redis-cluster documentation to start a cluster $ docker run --rm -p 6379:6379 redis:alpine
$ 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 Testnpm run test |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论