@axelspringer/graphql-google-pubsub

中文文档
2.1.0发布于 2020/02/13MITCommonJS近 30 天下载 7270

A graphql-subscriptions PubSub Engine using Google PubSub

原始使用文档
文档目录11 节
  1. Installation
  2. Using as AsyncIterator
  3. Receive Messages
  4. Dynamically use a topic based on subscription args passed o…
  5. Using both arguments and payload to filter events
  6. Creating the Google PubSub Client
  7. Options
  8. topic2SubName
  9. commonMessageHandler
  10. Author
  11. Acknowledgements

graphql-google-pubsub

This 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

npm install @axelspringer/graphql-google-pubsub or yarn add @axelspringer/graphql-google-pubsub

Using as AsyncIterator

Define your GraphQL schema with a Subscription type:

schema {
  query: Query
  mutation: Mutation
  subscription: Subscription
}

type Subscription {
    somethingChanged: Result
}

type Result {
    id: String
}

Now, let's create a simple GooglePubSub instance:

import { GooglePubSub } from '@axelspringer/graphql-google-pubsub';
const pubsub = new GooglePubSub();

Now, implement your Subscriptions type resolver, using the pubsub.asyncIterator to map the event you need:

const SOMETHING_CHANGED_TOPIC = 'something_changed';

export const resolvers = {
  Subscription: {
    somethingChanged: {
      subscribe: () => pubsub.asyncIterator(SOMETHING_CHANGED_TOPIC),
    },
  },
}

Subscriptions resolvers are not a function, but an object with subscribe method, that returns AsyncIterable.

Calling the method asyncIterator of the GooglePubSub instance will subscribe to the topic provided and will return an AsyncIterator binded to the GooglePubSub instance and listens to any event published on that topic. Now, the GraphQL engine knows that somethingChanged is a subscription, and every time we will use pubsub.publish over this topic, the GooglePubSub will PUBLISH the event 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.

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 Messages

The 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 can use custom message handler test illustrates the flexibility of the common message handler.

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 events

import { 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 Client

import { GooglePubSub } from '@axelspringer/graphql-google-pubsub';

const pubSub = new GooglePubSub(options, topic2SubName, commonMessageHandler)

Options

These 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 Options

Subscription options can be passed into subscribe or asyncInterator.

Note: google.protobuf.Duration types must be passed in as an object with a seconds property ({ seconds: 123 }).

const dayInSeconds = 60 * 60 * 24;

const subscriptionOptions = {
  messageRetentionDuration: { seconds: dayInSeconds },
  expirationPolicy: {
    ttl: { seconds: dayInSeconds * 2 }, // 2 Days
  },
};

await pubsub.asyncIterator("abc123", subscriptionOptions);

topic2SubName

Allows 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`

commonMessageHandler

The 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)
    },
  },
}

Author

Jonas Hackenberg - jonas-arkulpa

Acknowledgements

This 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).

版本与发布记录

@axelspringer/graphql-google-pubsub 共发布 18 个版本,首次发布于 2018/03/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.1.0latest2020/02/136 年前
2.0.02019/11/047 年前
1.2.12019/05/027 年前
1.2.02019/02/027 年前
1.1.32018/10/138 年前
1.1.22018/09/298 年前

关于 @axelspringer/graphql-google-pubsub 的常见问题

@axelspringer/graphql-google-pubsub 是什么?

A graphql-subscriptions PubSub Engine using Google PubSub

如何安装 @axelspringer/graphql-google-pubsub?

在项目目录运行 npm install @axelspringer/graphql-google-pubsub,或使用 pnpm add / yarn add / bun add。

@axelspringer/graphql-google-pubsub 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/axelspringer__graphql-google-pubsub 是否存在。

@axelspringer/graphql-google-pubsub 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@axelspringer/graphql-google-pubsub 可以商用吗?

@axelspringer/graphql-google-pubsub 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@axelspringer/graphql-google-pubsub 的下载量有多少?

根据 npm 官方下载统计,@axelspringer/graphql-google-pubsub 在 2026/10/08 – 2026/11/06 这 30 天内被下载 7,270 次,日均约 242 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@axelspringer/graphql-google-pubsub 还在维护吗?

最新版本 2.1.0 发布于 2020/02/13(6 年前);至今共发布 18 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/03/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。