在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):davidyaha/graphql-mqtt-subscriptions开源软件地址(OpenSource Url):https://github.com/davidyaha/graphql-mqtt-subscriptions开源编程语言(OpenSource Language):TypeScript 100.0%开源软件介绍(OpenSource Introduction):graphql-mqtt-subscriptionsThis package implements the AsyncIterator Interface and PubSubEngine Interface from the graphql-subscriptions package. It allows you to connect your subscriptions manager to an MQTT enabled Pub Sub broker to support horizontally scalable subscriptions setup. This package is an adapted version of my graphql-redis-subscriptions package. Installation
Using the AsyncIterator InterfaceDefine your GraphQL schema with a schema {
query: Query
mutation: Mutation
subscription: Subscription
}
type Subscription {
somethingChanged: Result
}
type Result {
id: String
} Now, create a import { MQTTPubSub } from 'graphql-mqtt-subscriptions';
const pubsub = new MQTTPubSub(); // connecting to mqtt://localhost by default Now, implement the Subscriptions type resolver, using const SOMETHING_CHANGED_TOPIC = 'something_changed';
export const resolvers = {
Subscription: {
somethingChanged: {
subscribe: () => pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC)
}
}
}
The When messages are received from the topic, those messages can be returned back to connected clients.
pubsub.publish(SOMETHING_CHANGED_TOPIC, { somethingChanged: { id: "123" }}); Dynamically Create a Topic Based on Subscription Args Passed on the Query:export const resolvers = {
Subscription: {
somethingChanged: {
subscribe: (_, args) => pubsub.asyncIterator(`${SOMETHING_CHANGED_TOPIC}.${args.relevantId}`),
},
},
} Using 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,
),
},
},
} Passing your own client objectThe basic usage is great for development and you will be able to connect to any mqtt enabled server running on your system seamlessly. For production usage, it is recommended you pass your own MQTT client. import { connect } from 'mqtt';
import { MQTTPubSub } from 'graphql-mqtt-subscriptions';
const client = connect('mqtt://test.mosquitto.org', {
reconnectPeriod: 1000,
});
const pubsub = new MQTTPubSub({
client
}); You can learn more on the mqtt options object here. Changing QoS for publications or subscriptionsAs specified here, the MQTT.js publish and subscribe functions takes an
options object. This object can be defined per trigger with const triggerToQoSMap = {
'comments.added': 1,
'comments.updated': 2,
};
const pubsub = new MQTTPubSub({
publishOptions: trigger => Promise.resolve({ qos: triggerToQoSMap[trigger] }),
subscribeOptions: (trigger, channelOptions) => Promise.resolve({
qos: Math.max(triggerToQoSMap[trigger], channelOptions.maxQoS),
}),
}); Get Notified of the Actual QoS Assigned for a SubscriptionMQTT allows the broker to assign different QoS levels than the one requested by the client.
In order to know what QoS was given to your subscription, you can pass in a callback called const onMQTTSubscribe = (subId, granted) => {
console.log(`Subscription with id ${subId} was given QoS of ${granted.qos}`);
}
const pubsub = new MQTTPubSub({onMQTTSubscribe}); Change Encoding Used to Encode and Decode MessagesSupported encodings available here const pubsub = new MQTTPubSub({
parseMessageWithEncoding: 'utf16le',
}); Basic Usage with SubscriptionManager (Deprecated)import { MQTTPubSub } from 'graphql-mqtt-subscriptions';
const pubsub = new MQTTPubSub(); // connecting to mqtt://localhost on default
const subscriptionManager = new SubscriptionManager({
schema,
pubsub,
setupFunctions: {},
}); Using Trigger Transform (Deprecated)Similar to the graphql-redis-subscriptions package, this package supports
a trigger transform function. This trigger transform allows you to use the Here is an example of a generic trigger transform. const triggerTransform = (trigger, { path }) => [trigger, ...path].join('.');
Next, pass the const pubsub = new MQTTPubSub({
triggerTransform,
}); Lastly, a setupFunction is provided for the const subscriptionManager = new SubscriptionManager({
schema,
setupFunctions: {
commentsAdded: (options, { repoName }) => ({
'comments/added': {
channelOptions: { path: [repoName] },
},
}),
},
pubsub,
});
When const query = `
subscription X($repoName: String!) {
commentsAdded(repoName: $repoName)
}
`;
const variables = {repoName: 'graphql-mqtt-subscriptions'};
subscriptionManager.subscribe({ query, operationName: 'X', variables, callback }); The subscription string that MQTT will receive will be |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论