# @codecompose/typed-pubsub 中文文档

规范地址：https://npmcn.com/package/%40codecompose/typed-pubsub/

版本：1\.2\.1
npm 元数据更新时间：2026-03-14T18:38:12.627Z
中文译文更新时间：2026-11-10T06:35:03.961Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40codecompose/typed-pubsub
原文对照：https://npmcn.com/package/%40codecompose/typed-pubsub/?lang=original
项目主页：https://github.com/0x80/typed-pubsub#readme
源码仓库：https://github.com/0x80/typed-pubsub

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：48 kB，16 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@google-cloud/pubsub \>=4，firebase-functions \>=6，zod \>=3
- 首次发布：2025-04-07T20:12:32.305Z
- 最新版本发布：2026-03-14T18:38:12.370Z
- 近 30 天下载量：3345（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：6（近 12 个月 2 个）

## 中文简介

用于 Google Cloud 和 Firebase 的型式安全酒吧/子抽象

## 安装

```sh
npm install @codecompose/typed-pubsub
```

也可以使用：`pnpm add @codecompose/typed-pubsub`、`yarn add @codecompose/typed-pubsub`、`bun add @codecompose/typed-pubsub`

## README

# 键入- pubsub

用于Google Cloud和Firebase的型式安全 PubSub抽象.

## 特征

-   **类型安全通讯**: 对出版商和处理者的完整类型脚本支持
-   **运行时间验证**: 使用 Zod 的 Schema 校验可以防止无效信件
-   **重复预防**: 防止重复的可选事件标记 处理
-   **存储信件处理**: 选择基于时间发送信件
-   **自定义默认**: 配置您自己的全库默认值 每个手控器都超过 箱外的你得到:
    -   以7天的指数回放启用复写
    -   缩放到每个话题最多250个实例( 比 Firebase 默认安全) 三千亿
    -   每例512MB 内存分配

## 安装

```bash
npm install @codecompose/typed-pubsub
```

## 同伴依赖关系

此软件包具有以下对等依赖性:

-   `@google-cloud/pubsub`
-   `firebase-functions`
-   `zod`

## 快速启动

1.  与 Zod 定义您的信件计划
2.  创建 PubSub 客户端
3.  用您的计划初始化已键入的 PubSub
4.  创建类型安全出版社和处理器

```typescript
import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { z } from "zod";

// 1. Define your schemas
const schemas = {
  user_created: z.object({
    userId: z.string(),
    email: z.string().email(),
  }),
};

// 2. Create PubSub client
const client = new PubSub();

// 3. Initialize typed PubSub
const pubsub = createTypedPubsub({
  client,
  schemas,
  region: "us-central1",
});

// 4a. Create and use a publisher
await pubsub.createPublisher("user_created")({
  userId: "123",
  email: "user@example.com",
});

// 4b. Create a handler
export const handle_user_created = pubsub.createHandler({
  topic: "user_created",
  handler: async (data) => {
    // data is fully typed based on the schema
    console.log(`New user created: ${data.email}`);
  },
});
```

## 用法实例

### 基本设置

```typescript
import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { z } from "zod";

// Define your schemas
const schemas = {
  user_created: z.object({
    userId: z.string(),
    email: z.string().email(),
    createdAt: z.string().datetime(),
  }),
  order_placed: z.object({
    orderId: z.string(),
    userId: z.string(),
    items: z.array(
      z.object({
        productId: z.string(),
        quantity: z.number().int().positive(),
      }),
    ),
    total: z.number().positive(),
  }),
};

// Create typed Pubsub client
const pubsub = createTypedPubsub({
  client: new PubSub(),
  schemas,
  region: "us-central1",
});

// Publish a message
await pubsub.createPublisher("user_created")({
  userId: "123",
  email: "user@example.com",
  createdAt: new Date().toISOString(),
});

// Create a handler
export const handle_order_placed = pubsub.createHandler({
  topic: "order_placed",
  handler: async (data) => {
    // data is fully typed based on the schema
    console.log(`Processing order ${data.orderId} for user ${data.userId}`);
    // Process the order...
  },
  options: {
    memory: "1GiB",
    timeoutSeconds: 60,
    markEvent: true, // Never process this event more than once
  },
});
```

> **说明:** 例子使用 srave case来表示主题名称( 如“ user created ” ) 和导出云函数(像 handle order placed)。 这是因为 外壳目前在GCP中的 Cloud Run 函数名中被忽略, 因此使用 用于一致性的蛇 case 优先.

### 防止与事件标记重复处理

PubSub有至少一次发送的语义,意思是信息有时可能 不止一次交付。 对于必须执行一次的行动 (如支付处理或用户信用奖),此库提供事件 标记.

这个 `markEvent` 选项使用您提供的存储器( 如 Redis) 来跟踪 已处理事件标识,确保每个事件得到准确处理 一次,尽管 潜在的再加工.

```typescript
import { PubSub } from "@google-cloud/pubsub";
import { createTypedPubsub } from "@codecompose/typed-pubsub";
import { redis } from "./redis-client";

// Create event marking functions
const eventMarkingFunctions = {
  isEventProcessed: async (eventId) => {
    return Boolean(await redis.get(`event:${eventId}`));
  },
  markEventAsProcessed: async (eventId) => {
    await redis.set(`event:${eventId}`, "1", "EX", 86400); // 24 hours TTL
  },
};

// Create typed Pubsub client with event marking
const pubsub = createTypedPubsub({
  client: new PubSub(),
  schemas,
  region: "us-central1",
  options: {
    eventMarkingFunctions,
    defaultHandlerOptions: {
      markEvent: true, // Enable for all handlers by default
      vpcConnector: "redis-connector", // If Redis is in a VPC
    },
  },
});
```

### 处理时间敏感事件

对于时间敏感的操作,您可能想要丢弃太过的消息 老样子 这个 `retryMaxAgeMinutes` 选项自动减少超过 指定年龄,防止处理陈旧数据.

```typescript
// Configure time-based message dropping in the handler
export const handle_time_sensitive_events = pubsub.createHandler({
  topic: "time_sensitive_events",
  handler: async (data) => {
    // Process time-sensitive event
  },
  options: {
    retryMaxAgeMinutes: 60, // Only process events less than 1 hour old
  },
});
```

## API 参考

### `createTypedPubsub(options)`

创建一个类型安全的 Pubsub 客户端, 用于使用 schema 验证处理信件 .

#### 参数

-   `client`: Google Cloud Pubsub 客户端实例
-   `schemas`: 每一专题的Zod计划记录
-   `region`: 用于 Pubsub 函数的 GCP 区域
-   `options`: (可选) 配置选项
    -   `eventMarkingFunctions`: (可选)跟踪已处理事件的职能
    -   `defaultHandlerOptions`: (可选) 所有处理器的默认选项
-   `onMessagePublished`: (可选) Firebase 消息已发布处理器, 默认值 用于实施火基地

### 密钥处理器选项

| 选项 | 说明 | 默认 |
| --- | --- | --- |
| `retry` | 启用/ 禁用自动重试 | `true` |
| `retryMaxAgeMinutes` | 下降前的最大事件年龄 | `undefined` (无限制) |
| `memory` | 内存分配 | `"512MiB"` |
| `markEvent` | 允许重复预防 | `false` |
| `timeoutSeconds` | 函数超时秒 | `20` |
| `maxInstances` | 最大并行实例 | `250` |
| `vpcConnector` | VPC 连接器的名称 | `undefined` |

**关于重试行为的重要注释**: 当您可以启用/ 无法重试时 并设定重试事件的最大年龄,实际重试时间由 pubSub 订阅的 ACK 截止日期, 而不是 `timeoutSeconds` 设置。 这个 超时会关闭服务器进程, 但事件将只进行重试 aCK 最后期限到期后, 无法通过此库配置 .

## 限制和替代办法

虽然这个库提供了极佳的种类安全和计划验证 PubSub消息, PubSub 有一些固有的限制:

-   对重试时间的控制有限(由订阅ACK截止日期控制)
-   没有内置支持手动触发重试
-   没有针对不同故障情形的精细错误处理

如果您使用时需要更高级的功能, 如控制重试 间隔、 手动重试触发或长期背景进程, 考虑使用专门的任务队列系统。 这个 [键入任务](https://github.com/0x80/typed-tasks) 库提供类似的 类型安全保障,对任务执行有更严格的控制.

## 常见问题

### @codecompose/typed-pubsub 是什么？

用于 Google Cloud 和 Firebase 的型式安全酒吧/子抽象

### 如何安装 @codecompose/typed-pubsub？

在项目目录运行 npm install @codecompose/typed-pubsub，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@google-cloud/pubsub（\>=4）、firebase-functions（\>=6）、zod（\>=3）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @codecompose/typed-pubsub 支持 TypeScript 吗？

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

### @codecompose/typed-pubsub 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @codecompose/typed-pubsub 可以商用吗？

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

### @codecompose/typed-pubsub 的下载量有多少？

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

### @codecompose/typed-pubsub 还在维护吗？

最新版本 1\.2\.1 发布于 2026/03/15（7 个月前）；至今共发布 6 个版本，其中过去 12 个月发布了 2 个；首次发布于 2025/04/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

