在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):axelspringer/graphql-google-pubsub开源软件地址(OpenSource Url):https://github.com/axelspringer/graphql-google-pubsub开源编程语言(OpenSource Language):TypeScript 100.0%开源软件介绍(OpenSource Introduction):graphql-google-pubsubThis package implements the PubSubEngine Interface from the graphql-subscriptions package and also the new AsyncIterator interface. It allows you to connect your subscriptions manger to a Google PubSub mechanism to support multiple subscription manager instances. Installation
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 { GooglePubSub } from '@axelspringer/graphql-google-pubsub';
const pubsub = new GooglePubSub(); 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" }}); The topic doesn't get created automatically, it has to be created beforehand. If you publish non string data it gets stringified and you have to parse the received message data. Receive MessagesThe received message from Google PubSub gets directly passed as payload to the resolve/filter function. You might extract the data (Buffer) in there or use a common message handler to transform the received message. function commonMessageHandler ({attributes = {}, data = ''}) {
return {
...attributes,
text: data.toString()
};
} The Dynamically use 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 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 Google PubSub Clientimport { GooglePubSub } from '@axelspringer/graphql-google-pubsub';
const pubSub = new GooglePubSub(options, topic2SubName, commonMessageHandler) OptionsThese are the options which are passed to the internal or passed Google PubSub client. The client will extract credentials, project name etc. from environment variables if provided. Have a look at the authentication guide for more information. Otherwise you can provide this details in the options. const options = {
projectId: 'project-abc',
credentials:{
client_email: '[email protected]',
private_key: '-BEGIN PRIVATE KEY-\nsample\n-END PRIVATE KEY-\n'
}
}; Subscription OptionsSubscription options can be passed into Note: google.protobuf.Duration types must be passed in as an object with a seconds property ( const dayInSeconds = 60 * 60 * 24;
const subscriptionOptions = {
messageRetentionDuration: { seconds: dayInSeconds },
expirationPolicy: {
ttl: { seconds: dayInSeconds * 2 }, // 2 Days
},
};
await pubsub.asyncIterator("abc123", subscriptionOptions); topic2SubNameAllows building different workflows. If you listen on multiple server instances to the same subscription, the messages will get distributed between them. Most of the time you want different subscriptions per server. That way every server instance can inform their clients about a new message. const topic2SubName = topicName => `${topicName}-${serverName}-subscription` commonMessageHandlerThe common message handler gets called with the received message from Google PubSub. You can transform the message before it is passed to the individual filter/resolver methods of the subscribers. This way it is for example possible to inject one instance of a DataLoader which can be used in all filter/resolver methods. const getDataLoader = () => new DataLoader(...);
const commonMessageHandler = ({attributes: {id}, data}) => ({id, dataLoader: getDataLoader()}); export const resolvers = {
Subscription: {
somethingChanged: {
resolve: ({id, dataLoader}) => dataLoader.load(id)
},
},
} AuthorJonas Hackenberg - jonas-arkulpa AcknowledgementsThis project is mostly inspired by graphql-redis-subscriptions. Many thanks to its authors for their work and inspiration. Thanks to the Lean Team (Daniel Vogel, Martin Thomas, Marcel Dohnal, Florian Tatzky, Sebastian Herrlinger, Mircea Craculeac and Tim Susa). |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论