@francoca87/nestjs-google-pubsub-connector

中文文档
2.2.0发布于 2026/08/08ISCTypeScriptCommonJS构建来源已验证近 30 天下载 4137

Google PubSub 的 NestJS 连接器

中文使用文档
文档目录11 节
  1. 特征
  2. 微型服务战略
  3. 装饰者
  4. 订阅创建
  5. 敲打和纳克
  6. 使用量
  7. 一次处理
  8. 客户代理
  9. 使用量
  10. 认证
  11. 实例

NestJS Google Pubsub 连接器

npm latest version

从 flocasts/nestjs-google-pubsub 连接器

这个软件包包括两个部件,一个NestJS微服务策略和一个客户端代理. 这样一来,就能 以NestJS-y的方式轻松地与Google PubSub整合.

特征

  • 将您的订阅听众作为控制器整合到强大的 NestJS 框架中!
  • 按需创建订阅,采用自助命名策略!!
  • “just-works”方法意味着需要从框外插入零配置,只需插入 并让框架来做其余的工作.
  • 哦,那么广:
    • 订阅命名策略允许您动态命名订阅方式 你们 想要吗!
    • Ack/nack 策略让您将您的商业逻辑与您如何响应消息解开!
  • 装饰者! 装饰者! 装饰者!

微型服务战略

在创建微服务时,将服务器/运输战略部分作为战略插入 很少配置参数, 以及可选的 PubSub 实例, 例如 :

async function bootstrap() {
    const app: INestMicroservice = await NestFactory.createMicroservice<MicroserviceOptions>(
        ExampleModule,
        {
            strategy: new GooglePubSubTransport({
                createSubscriptions: true,
                // The microservice will configure its own PubSub instance, but you're free to
                // supply your own
                // client: new PubSub()
            }),
        },
    );

    // It's also possible to connect as a hybrid app:
    // const app = await NestFactory.create(HttpAppModule);
    // const microservice = app.connectMicroservice({
    //      strategy: new GooglePubSubTransport({
    //          createSubscriptions: true,
    //          // The microservice will configure its own PubSub instance, but you're free to
    //          // supply your own
    //          // client: new PubSub
    //      }),
    // });

    return app.listen(() => {
        console.log('example app started!');
    });
}
bootstrap();

只要上面的配置,您就可以有工作控制器在几分钟内响应消息.

装饰者

参数装饰器是雀巢JS中最易使用的功能之一,这个库提供了一些 这将让解析 PubSub 信件变得简单、简单和有趣:

名称说明
@ GooglePubSubMessageHandler (英语)使用订阅名称和可选的订阅主题名称和创建参数. 尚未退出的订阅将创建 若为: 提供了主题名称 财务报告和审定财务报表 createSubscriptions 当微服务创建时被设定为真实。 创建参数为类型 CreateSubscriptionOptions 从google 酒吧/子图书馆
@GooglePubSubMessageBody (英语)这个会取回 JSON.parse() 发送信件的正文。 您可以选择包含一个密钥,相应的值将被返回.
@ GooglePub SubMessage 属性这将检索来信的属性 。 您可以选择包含一个密钥, 相应的值将被返回 .
@ GooglePubSubMessage 交付尝试这将返回此消息的发送尝试次数 。 只有订阅有"死信队列"时,才会递增.
@ GooglePubSubMessageId (英语)这将返回消息的ID .
亚克这将返回函数 ack 正在发送的消息.
不详. 这将禁用任何自动搜索 .
@纳克与上相同,但为 n.

订阅创建

若为 createSubscriptions 被设定为真实的运输器设置, 然后服务会 尝试创建新订阅, 如果请求的订阅是处理器 尚未出现。 微服务需要一个 subscriptionNamingStrategy 作为 参数,它需要符合 SubscriptionNamingStrategy 接口。 默认情况下包含一个基本策略:

import { SubscriptionNamingStrategy } from '@francoca87/nestjs-google-pubsub-microservice';
import { NamingDependencyTag, SubscriptionNameDependencies } from './interfaces';

export class BasicSubscriptionNamingStrategy implements SubscriptionNamingStrategy {
    public generateSubscriptionName(deps: SubscriptionNameDependencies): string {
        switch (deps._tag) {
            case NamingDependencyTag.TOPIC_AND_SUBSCRIPTION_NAMES:
            case NamingDependencyTag.SUBSCRIPTION_NAME_ONLY:
                return deps.subscriptionName;
            case NamingDependencyTag.TOPIC_NAME_ONLY:
                return `${deps.topicName}-sub`;
        }
    }
}

从此策略返回的字符串将作为创建订阅的名称.

敲打和纳克

为了让用户 拥有自己命运的力量 图书馆既使用手动方式,又使用“只管工作”的方法来敲打和敲打 留言。 这是通过“战略”确认 AckStrategy, (中文(简体) ), NackStrategy 在运输创建时提供的接口.

阿克战略

Ack策略保证在操作成功后运行 显示连接和反锁信件的功能以及信件 GooglePubSubContext。默认情况如下:

import { GooglePubSubContext } from '../ctx-host';
import { AckFunction, AckStrategy, NackFunction } from '../interfaces';

export class BasicAckStrategy implements AckStrategy {
    public ack(ack: AckFunction, nack: NackFunction, ctx: GooglePubSubContext): Promise<void> {
        if (ctx.getAutoAck()) {
            ack();
        }
        return Promise.resolve();
    }
}

这里的流量很简单, 如果自动Ack被设定为真实, 此消息将会被触发 函数将返回.

纳克战略

如果处理器出现出错, 保证纳克策略运行 .
不详. 这将发生于( A) 例外过滤器。
除了抛出错误外, 签名与 Ack 策略相同 (pun意向)作为第一个论据列入。 默认情况如下:

import { GooglePubSubContext } from '../ctx-host';
import { AckFunction, NackFunction, NackStrategy } from '../interfaces';

export class BasicNackStrategy implements NackStrategy {
    public nack(
        error: Error,
        ack: AckFunction,
        nack: NackFunction,
        ctx: GooglePubSubContext,
    ): Promise<void> {
        if (ctx.getAutoNack()) {
            nack();
        }
        return Promise.resolve();
    }
}

没有战略/狂欢的敲打和敲打

除了使用这些战略外,图书馆还提供Ack和Nack 通过装饰器到控制器以及从 页:1 GooglePubSubContext当 ack 或 nack 函数为 从上下文中检索(直接或通过 装饰) 自动Ack/自动纳克方法会返回虚假, (中文(简体) ), 禁用基本策略和任意策略 应选择创建.

使用量

// src/main.ts
import { NestFactory } from '@nestjs/core';
import {
    GooglePubSubTransport,
} from '@francoca87/nestjs-google-pubsub-microservice';
import { TestModule } from './test.module';

async function bootstrap() {
    const app = await NestFactory.createMicroservice(TestModule, {
        strategy: new GooglePubSubTransport({
            createSubscriptions: true,
            // The microservice will configure its own PubSub instance, but you're free to
            // supply your own
            // client: new PubSub
        }),
    });
    return app.listen(() => {
        console.log('app started!');
    });
}

bootstrap();

// src/test.module.ts
import { Module } from '@nestjs/common';
import { TestController } from './test.controller';

@Module({
    controllers: [TestController],
})
export class TestModule {
}

// src/test.controller.ts
import { Controller } from '@nestjs/common';
import {
    GooglePubSubMessageBody,
    GooglePubSubMessageHandler,
} from '@francoca87/nestjs-google-pubsub-microservice';

@Controller()
export class TestController {
    constructor(
        private readonly diService: DiService,
    ) {
    }

    @GooglePubSubMessageHandler({
        subscriptionName: 'my-existing-subscription',
    })
    public handler1(@GooglePubSubMessageBody() data: { foo: boolean }): void {
        return this.diService.handleFoo(data);
    }

    @GooglePubSubMessageHandler({
        subscriptionName: 'my-subscription-that-or-may-not-exist',
        createOptions: {
            enableMessageOrdering: true,
        },
        topicName: 'my-existing-topic',
    })
    public handler2(@GooglePubSubMessageBody('bar') bar: boolean): void {
        return this.diService.handleBar(data);
    }
}

一次处理

库允许您选择是并行处理您的信件( PubSub 的标准) 还是连续处理 。 仅仅允许 oneAtATime 您的配置选项中的旗帜 @GooglePubSubMessageHandler 装饰. 一旦启用,在处理器返回或丢出出错误之前,不会拖动新信件 。 禁用或删除旗将行为重置为默认 .

不详. 这只在您申请的单一情况下有效。 如果运行在 kubernetes 集群或其他水平缩放环境中, 请考虑将您的应用程序创建为单通 .

    @GooglePubSubMessageHandler({
        subscriptionName: 'my-subscription-that-or-may-not-exist',
        topicName: 'my-existing-topic',
        oneAtATime: true //true for serial handling, false or blank for default
    })
    public handler2(@GooglePubSubMessageBody('bar') bar:  boolean ): void {
        return this.diService.handleBar(data);
    }

客户代理

这个库还提供了一个基本客户端代理,将一个 PubSub 实例包起来.

此代理支持 :

  • 出版
  • 专题/订阅创建
  • 专题/订阅删除

您可以在 示例目录。 。 。 .

使用量

import { ClientGooglePubSub } from '@francoca87/nestjs-google-pubsub-microservice';

const msg = 'beam me up scotty';

new ClientGooglePubSub().publishToTopic('my-test-topic', Buffer.from(msg));

认证

按照本库的"公正工作"方式,认证是完全处理的 由PubSub客户端提供 这就是说,缔约方会议指出的全权证书 GOOGLE_APPLICATION_CREDENTIALS 如果 PUBSUB_EMULATOR_HOST 已经设定。 如果你需要更高级的 配置, 然后传输策略和客户端代理都会使用 PubSub 客户端实例 作为构造参数 - 您可以简单地构建所需的客户端, 然后将其交出 .

实例

可在 示例目录。 。 。 .

运行示例服务器的前提条件

要运行示例服务器,您必须:

  • 有过 GOOGLE_APPLICATION_CREDENTIALS ,指向有效证书,或
  • 拥有运行中的 PubSub 仿真器 PUBSUB_EMULATOR_HOST 设置在您的环境中

在这两种情况下,您都需要创建示例服务器中的任何主题(或将其更改为 专题).

运行示例服务器

要运行服务器,只需引用提供的 npm 脚本 :

npm run example:server

假设所有先决条件都得到满足,你应该看到类似以下的东西:

> @francoca87/[email protected] example:server /Users/francocarreras/repos/nestjs-google-pubsub-transport
> node --inspect -r ts-node/register examples/server/main.ts

Debugger listening on ws://127.0.0.1:9229/d23772bb-0e6d-40f8-b47d-d0fc94c7c8c2
For help, see: https://nodejs.org/en/docs/inspector
[Nest] 90792   - 04/17/2021, 7:04:02 PM   [NestFactory] Starting Nest application...
[Nest] 90792   - 04/17/2021, 7:04:02 PM   [InstanceLoader] ExampleService dependencies initialized +28ms
[Nest] 90792   - 04/17/2021, 7:04:02 PM   [InstanceLoader] ExampleModule dependencies initialized +0ms
[Nest] 90792   - 04/17/2021, 7:04:02 PM   [NestMicroservice] Nest microservice successfully started +5ms
[Nest] 90792   - 04/17/2021, 7:04:02 PM   [GooglePubSubTransport] Mapped {projects/francocarreras-174016/subscriptions/lee-christmas-notifications} handler
example app started!

版本与发布记录

@francoca87/nestjs-google-pubsub-connector 共发布 7 个版本,首次发布于 2026/05/15;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.2.0latest2026/08/083 个月前
2.1.02026/08/083 个月前
2.0.02026/08/083 个月前
1.0.32026/06/194 个月前
1.0.22026/05/275 个月前
1.0.12026/05/156 个月前

关于 @francoca87/nestjs-google-pubsub-connector 的常见问题

@francoca87/nestjs-google-pubsub-connector 是什么?

Google PubSub 的 NestJS 连接器

如何安装 @francoca87/nestjs-google-pubsub-connector?

在项目目录运行 npm install @francoca87/nestjs-google-pubsub-connector,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@nestjs/common(>=10.0)、@nestjs/core(>=10.0)、@nestjs/microservices(>=10.0)、reflect-metadata(^0.2.2)、rxjs(>=7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@francoca87/nestjs-google-pubsub-connector 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@francoca87/nestjs-google-pubsub-connector 支持 ESM 还是 CommonJS?

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

@francoca87/nestjs-google-pubsub-connector 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@francoca87/nestjs-google-pubsub-connector 可以商用吗?

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

@francoca87/nestjs-google-pubsub-connector 的下载量有多少?

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

@francoca87/nestjs-google-pubsub-connector 还在维护吗?

最新版本 2.2.0 发布于 2026/08/08(3 个月前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2026/05/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。