# @authhero/adapter-interfaces 中文文档

规范地址：https://npmcn.com/package/%40authhero/adapter-interfaces/

版本：4\.26\.0
npm 元数据更新时间：2026-11-05T14:43:49.313Z
中文译文更新时间：2026-11-07T06:02:58.406Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40authhero/adapter-interfaces
原文对照：https://npmcn.com/package/%40authhero/adapter-interfaces/?lang=original
项目主页：https://authhero.net/
源码仓库：https://github.com/sesamyab/authhero

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

- 包体积（解压后）：1.7 MB，174 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@hono/zod-openapi ^1\.4\.0
- 首次发布：2024-07-17T08:14:59.099Z
- 最新版本发布：2026-11-05T14:43:48.936Z
- 近 30 天下载量：2344（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：272（近 12 个月 142 个）

## 中文简介

这个包提供了一套用于为AuthHero创建适配器的接口. 适配器被用来将AuthHero连接到各种服务,如数据库,电子邮件服务等等.

## 安装

```sh
npm install @authhero/adapter-interfaces
```

也可以使用：`pnpm add @authhero/adapter-interfaces`、`yarn add @authhero/adapter-interfaces`、`bun add @authhero/adapter-interfaces`

## README

# @authhero/适应器界面

这个包提供了一套用于为AuthHero创建适配器的接口. 适配器被用来将AuthHero连接到各种服务,如数据库,电子邮件服务等等.

## 数据库适配器

数据库适配器遵循这些规则:

-   创建的 at和被修改的 at字段由适配器在创建或更新记录时处理.
-   租户 id 字段不属于发送到适配器的实体.
-   实体代号被传递给适配器.
-   适配器可以通过AuthParams等对象. 这些物体一般会被平整为适配器的一部分.
-   适配器所使用的类型应当从zod schemas中推断出,以确保运行时的类型安全.
-   Id列和实体一般应该从实体名称开始,例如用户实体的用户 id. 我们从Auth0开始遵循命名方式,所以它可能并不总是一致的.
-   适配器通常应披露下列方法.
    -   `create(tenant_id: string, entity: Entity): Promise<Entity>`
    -   `update(tenant_id: string, entity: Entity): Promise<boolean>`
    -   `remove(tenant_id: string, entity: Entity): Promise<boolean>`
    -   `get(tenant_id: string, [entity_id]: string): Promise<Entity | null>`
    -   `list(tenant_id: string, query: Query): Promise<Entity[]>`

## 公用事业

### 通过适配器

这个 `createPassthroughAdapter` 工具允许您将操作同步到多个适配器执行中。 这对于:

-   **多目的地伐木**: 将日志写入数据库和分析服务
-   **缓存变暖**: 同步写入多个缓存层
-   **数据库迁移**: 逐步将数据从一个数据库迁移到另一个数据库

#### 基本用途

```typescript
import {
  createPassthroughAdapter,
  LogsDataAdapter,
} from "@authhero/adapter-interfaces";

// Primary adapter - all reads come from here, writes go here first
const primaryAdapter = createDatabaseLogsAdapter();

// Secondary adapter for analytics
const analyticsAdapter = createAnalyticsLogsAdapter();

// Create passthrough adapter
const logsAdapter = createPassthroughAdapter<LogsDataAdapter>({
  primary: primaryAdapter,
  secondaries: [
    {
      adapter: { create: analyticsAdapter.create },
      onError: (err) => console.error("Analytics sync failed:", err),
    },
  ],
});

// Usage
await logsAdapter.create("tenant-1", log); // Writes to both
const result = await logsAdapter.list("tenant-1"); // Reads from primary only
```

#### 配置选项

```typescript
interface PassthroughConfig<T> {
  // Primary adapter - all reads come from here, writes go here first
  primary: T;

  // Secondary adapters to sync writes to
  secondaries: {
    // Partial adapter implementation - only implemented methods will be called
    adapter: Partial<T>;

    // If true, wait for the secondary write to complete (default: false)
    blocking?: boolean;

    // Called when a secondary write fails
    onError?: (error: Error, method: string, args: unknown[]) => void;
  }[];

  // Methods to sync to secondaries (default: ["create", "update", "remove", "delete", "set"])
  syncMethods?: string[];
}
```

#### 仅写适应器帮助工具

使用 `createWriteOnlyAdapter` 明确说明辅助工具的方法:

```typescript
import {
  createWriteOnlyAdapter,
  createPassthroughAdapter,
} from "@authhero/adapter-interfaces";

const logsAdapter = createPassthroughAdapter({
  primary: databaseAdapter,
  secondaries: [
    {
      adapter: createWriteOnlyAdapter({
        create: async (tenantId, log) => {
          // Custom write logic (e.g., webhook, analytics)
        },
      }),
    },
  ],
});
```

#### 使用大小写

**多目的地日志 :**

```typescript
const logsAdapter = createPassthroughAdapter({
  primary: databaseLogsAdapter,
  secondaries: [
    { adapter: { create: analyticsEngineAdapter.create } },
    { adapter: { create: r2SqlAdapter.create } },
  ],
});
```

**以倒计时同步缓存 :**

```typescript
const cacheAdapter = createPassthroughAdapter({
  primary: redisCacheAdapter,
  secondaries: [{ adapter: memcachedAdapter, blocking: true }],
  syncMethods: ["set", "delete"],
});
```

## 常见问题

### @authhero/adapter-interfaces 是什么？

这个包提供了一套用于为AuthHero创建适配器的接口\. 适配器被用来将AuthHero连接到各种服务,如数据库,电子邮件服务等等\.

### 如何安装 @authhero/adapter-interfaces？

在项目目录运行 npm install @authhero/adapter-interfaces，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@hono/zod-openapi（^1\.4\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @authhero/adapter-interfaces 支持 TypeScript 吗？

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

### @authhero/adapter-interfaces 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @authhero/adapter-interfaces 可以商用吗？

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

### @authhero/adapter-interfaces 的下载量有多少？

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

### @authhero/adapter-interfaces 还在维护吗？

最新版本 4\.26\.0 发布于 2026/11/05（2 天前）；至今共发布 272 个版本，其中过去 12 个月发布了 142 个；首次发布于 2024/07/17。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

