npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

feishu-bitable-sdk

v1.0.0

Published

飞书多维表格中间层 SDK,提供简洁、类型安全的接口来执行CRUD操作

Readme

FeishuBitableSDK

项目简介

FeishuBitableSDK 是一个用于与飞书多维表格(Bitable)API 交互的 TypeScript SDK。它提供了简洁、类型安全的接口来对特定数据表执行增、删、改、查(CRUD)操作,作为业务后端与飞书服务之间的桥梁。

主要特性

  • 🚀 配置驱动: 通过简单的配置对象即可初始化SDK
  • 🔐 自动化认证: 自动处理 tenant_access_token 的获取和刷新
  • 👤 OAuth用户认证: 支持OAuth 2.0流程,获取用户级访问令牌
  • 📝 类型安全: 完整的 TypeScript 类型定义
  • 🛡️ 错误处理: 健壮的错误处理机制
  • 📚 完整文档: 详细的 JSDoc 注释和使用示例
  • 🧪 测试覆盖: 完整的单元测试和集成测试

认证方式

BitableSDK 支持两种认证方式:

1. 应用级认证(默认)

使用 appIdappSecret 进行应用级认证,适用于后台服务和系统集成。

2. 用户级认证(OAuth 2.0)

通过 OAuth 2.0 流程获取用户访问令牌,适用于需要区分具体用户的场景。

OAuth 使用方案

方案1: 手动OAuth(推荐用于开发测试)

# 运行手动OAuth演示
node examples/manual-oauth-demo.js
  • 不需要启动Web服务器
  • 手动获取授权码
  • 适用于开发测试和脚本运行

方案2: Web服务器OAuth(推荐用于生产环境)

# 启动OAuth服务器
node examples/oauth-server.js
  • 完整的OAuth流程
  • 自动处理回调
  • 适用于Web应用和生产环境

方案3: 应用级认证(现有功能)

const sdk = new BitableSDK(config);
  • 简单直接
  • 不需要用户交互
  • 适用于后台服务

详细使用指南请参考:使用指南

技术栈

  • 语言: TypeScript
  • 运行环境: Node.js (>= 16.0.0)
  • 模块系统: ES Modules (ESM)
  • 主要依赖: axios (HTTP 请求)
  • 测试框架: Jest
  • 构建工具: TypeScript Compiler

快速开始

1. 安装依赖

npm install feishu-bitable-sdk

2. 配置环境变量

创建 .env 文件并配置以下变量:

# 飞书应用配置
FEISHU_APP_ID=your_app_id_here
FEISHU_APP_SECRET=your_app_secret_here
FEISHU_BASE_ID=your_base_id_here
FEISHU_TABLE_ID=your_table_id_here

# OAuth配置(可选)
FEISHU_REDIRECT_URI=http://localhost:3000/oauth/callback
FEISHU_OAUTH_SCOPE=auth:user.id:read offline_access

3. 使用示例

应用级认证(推荐用于后台服务)

import { BitableSDK, ConfigManager } from 'feishu-bitable-sdk';

// 从.env文件获取配置
const config = ConfigManager.getFeishuConfig();

// 创建SDK实例
const sdk = new BitableSDK(config);

// 创建记录
const record = await sdk.addRecord('你好,世界!', 'user_001');

// 查询记录
const records = await sdk.listRecords('user_001');

// 更新记录
const updated = await sdk.updateRecord(record.id, 'Hello, World!');

// 删除记录
const result = await sdk.deleteRecord(record.id);

OAuth用户认证(推荐用于Web应用)

import { OAuthManager, UserBitableSDK, ConfigManager } from 'feishu-bitable-sdk';

// 从.env文件获取配置
const oauthConfig = ConfigManager.getOAuthConfig();
const bitableConfig = ConfigManager.getBitableConfig();

// 创建OAuth管理器
const oauthManager = new OAuthManager(oauthConfig);

// 生成授权URL
const authUrl = oauthManager.generateAuthUrl();

// 处理OAuth回调
const userAuth = await oauthManager.handleCallback(authorizationCode);

// 创建用户级SDK
const userSdk = UserBitableSDK.createWithOAuth(
  oauthConfig,
  bitableConfig.baseId,
  bitableConfig.tableId,
  userAuth
);

// 使用用户级SDK
const records = await userSdk.listUserRecords();

注意: 本SDK使用ES模块系统,确保你的项目支持ES模块。如果使用CommonJS,请使用动态导入:

const { BitableSDK } = await import('feishu-bitable-sdk');

OAuth认证流程

1. 飞书应用配置

在飞书开放平台配置您的应用:

  1. 启用OAuth功能

    • 进入应用详情页面
    • 在"开发配置"中启用OAuth功能
  2. 配置授权回调地址

    • 设置重定向URL(如:https://your-app.com/oauth/callback
    • 确保URL可以被飞书访问
  3. 申请权限

    • 申请 auth:user.id:read 权限
    • 如需刷新令牌,申请 offline_access 权限

2. OAuth流程步骤

sequenceDiagram
    participant User as 用户
    participant App as 您的应用
    participant OAuth as OAuth管理器
    participant Feishu as 飞书API
    
    User->>App: 点击登录
    App->>OAuth: generateAuthUrl()
    OAuth-->>App: 返回授权URL
    App->>User: 重定向到飞书授权页
    User->>Feishu: 授权应用
    Feishu->>App: 回调code
    App->>OAuth: handleCallback(code)
    OAuth->>Feishu: 交换user_access_token
    Feishu-->>OAuth: 返回token
    OAuth-->>App: 返回UserAuthInfo
    App->>User: 登录成功

3. Web服务器集成示例

// Express.js 示例
import express from 'express';
import { OAuthManager, UserBitableSDK } from 'feishu-bitable-sdk';

const app = express();
const oauthManager = new OAuthManager(oauthConfig);

// 登录页面
app.get('/login', (req, res) => {
  const authUrl = oauthManager.generateAuthUrl();
  res.redirect(authUrl);
});

// OAuth回调处理
app.get('/oauth/callback', async (req, res) => {
  const { code, state, error } = req.query;
  
  if (error) {
    return res.status(400).json({ error: 'OAuth授权失败' });
  }
  
  try {
    const userAuth = await oauthManager.handleCallback(code, state);
    
    // 存储用户认证信息
    req.session.userAuth = userAuth;
    
    res.json({ success: true, message: 'OAuth认证成功' });
  } catch (error) {
    res.status(500).json({ error: 'OAuth处理失败' });
  }
});

// 用户数据操作
app.get('/api/records', async (req, res) => {
  const userAuth = req.session.userAuth;
  if (!userAuth) {
    return res.status(401).json({ error: '用户未认证' });
  }
  
  const userSdk = UserBitableSDK.createWithOAuth(
    oauthConfig,
    baseId,
    tableId,
    userAuth
  );
  
  const records = await userSdk.listUserRecords();
  res.json({ records });
});

API 文档

配置接口

应用级SDK配置

interface BitableSDKConfig {
  appId: string;        // 飞书应用的 App ID
  appSecret: string;    // 飞书应用的 App Secret
  baseId: string;       // 多维表格的 ID
  tableId: string;      // 数据表的 ID
}

OAuth配置

interface OAuthConfig {
  appId: string;           // 飞书应用的 App ID
  appSecret: string;       // 飞书应用的 App Secret
  redirectUri: string;     // 授权回调地址
  scope?: string[];        // 请求的权限范围
  state?: string;          // 状态参数
}

用户级SDK配置

interface UserBitableSDKConfig {
  baseId: string;          // 多维表格的 ID
  tableId: string;         // 数据表的 ID
  userAuth: UserAuthInfo;  // 用户认证信息
}

记录数据模型

interface PromptRecord {
  id: string;           // 飞书记录 record_id
  提示词: string;       // 提示词内容
  作者: string;         // 创建该记录的用户ID
  日期: number;         // Unix时间戳(秒)
}

主要方法

应用级SDK方法

listRecords(authorId: string): Promise<PromptRecord[]>

根据作者ID查询其创建的所有记录。

const records = await sdk.listRecords('user_001');
console.log(`查询到 ${records.length} 条记录`);
addRecord(prompt: string, authorId: string): Promise<PromptRecord>

创建一条新的提示词记录。

const record = await sdk.addRecord('你好,世界!', 'user_001');
console.log('创建成功:', record);
updateRecord(recordId: string, newPrompt: string): Promise<PromptRecord>

根据记录ID更新指定的提示词内容。

const updated = await sdk.updateRecord('rec123', 'Hello, New World!');
console.log('更新成功:', updated);
deleteRecord(recordId: string): Promise<{ deleted: boolean }>

根据记录ID删除一条记录。

const result = await sdk.deleteRecord('rec123');
console.log('删除成功:', result.deleted);

用户级SDK方法

listUserRecords(pageSize?: number, pageToken?: string): Promise<PromptRecord[]>

获取当前用户的所有记录。

const records = await userSdk.listUserRecords();
console.log(`获取到 ${records.length} 条记录`);
addUserRecord(prompt: string): Promise<PromptRecord>

以当前用户身份创建一条新记录。

const record = await userSdk.addUserRecord('用户创建的记录');
console.log('创建成功:', record);
updateUserRecord(recordId: string, newPrompt: string): Promise<PromptRecord>

以当前用户身份更新记录。

const updated = await userSdk.updateUserRecord('rec123', '更新后的内容');
console.log('更新成功:', updated);
deleteUserRecord(recordId: string): Promise<{ deleted: boolean }>

以当前用户身份删除记录。

const result = await userSdk.deleteUserRecord('rec123');
console.log('删除成功:', result.deleted);
refreshUserToken(scope?: string[]): Promise<UserAuthInfo>

刷新用户访问令牌。

const newUserAuth = await userSdk.refreshUserToken();
console.log('令牌刷新成功');

OAuth管理器方法

generateAuthUrl(state?: string, scope?: string[]): string

生成OAuth授权URL。

const authUrl = oauthManager.generateAuthUrl();
console.log('授权URL:', authUrl);
handleCallback(code: string, state?: string, codeVerifier?: string): Promise<UserAuthInfo>

处理OAuth回调,获取用户访问令牌。

const userAuth = await oauthManager.handleCallback(code, state);
console.log('OAuth认证成功');
refreshUserToken(refreshToken: string, scope?: string[]): Promise<UserAuthInfo>

刷新用户访问令牌。

const newUserAuth = await oauthManager.refreshUserToken(refreshToken);
console.log('令牌刷新成功');

调试方法

应用级SDK

  • getConfig(): BitableSDKConfig - 获取当前SDK配置信息
  • getAuthInfo(): { token: string; expireTime: number } | null - 获取当前认证token信息
  • clearAuthCache(): void - 清除认证缓存

用户级SDK

  • getUserAuthInfo(): UserAuthInfo - 获取当前用户认证信息
  • getOAuthManager(): OAuthManager - 获取OAuth管理器
  • getUserAuthManager(): UserAuthManager - 获取用户认证管理器
  • clearAuthCache(): void - 清除认证缓存

错误处理

SDK 提供了完善的错误处理机制:

try {
  const records = await sdk.listRecords('user_001');
} catch (error) {
  if (error instanceof AuthError) {
    console.error('认证错误:', error.message);
  } else if (error instanceof APIError) {
    console.error('API错误:', error.message, error.code);
  } else {
    console.error('其他错误:', error.message);
  }
}

错误类型

  • BitableSDKError: 基础错误类
  • AuthError: 认证相关错误
  • APIError: API调用相关错误

开发环境设置

前置要求

  • Node.js (推荐 v16 或更高版本)
  • npm 或 yarn 包管理器

安装依赖

npm install

开发命令

# 启动开发服务器(监听文件变化)
npm run dev

# 构建项目
npm run build

# 运行测试
npm run test

# 代码检查
npm run lint

# 运行特定测试文件
node tests/test-add-record.ts
node tests/test-delete-record.ts
node tests/test-real-api.ts
node tests/debug-api-response.ts

# 运行OAuth演示
node examples/oauth-demo.ts

# 清理构建文件
npm run clean

项目结构

FeishuBitableSDK/
├── src/                    # 源代码目录
│   ├── types/             # 类型定义
│   │   └── index.ts       # 主要类型定义
│   ├── auth.ts            # 应用级认证管理模块
│   ├── oauth.ts           # OAuth认证管理模块
│   ├── userAuth.ts        # 用户认证管理模块
│   ├── api.ts             # 应用级API请求封装
│   ├── userApi.ts         # 用户级API请求封装
│   ├── BitableSDK.ts      # 应用级主SDK类
│   ├── UserBitableSDK.ts  # 用户级主SDK类
│   └── index.ts           # 主入口文件
├── examples/              # 使用示例
│   ├── demo.ts            # 应用级演示程序
│   ├── simple-demo.ts     # 简单示例
│   └── oauth-demo.ts      # OAuth演示程序
├── tests/                 # 测试文件
│   ├── setup.ts           # 测试设置
│   ├── BitableSDK.test.ts # 单元测试
│   ├── crud-integration.test.ts # CRUD集成测试
│   ├── error-handling.test.ts # 错误处理测试
│   ├── performance.test.ts # 性能测试
│   ├── concurrent.test.ts # 并发测试
│   ├── run-all-tests.ts   # 测试运行脚本
│   ├── test-add-record.ts # 添加记录测试(旧版)
│   ├── test-delete-record.ts # 删除记录测试(旧版)
│   ├── test-real-api.ts   # 真实API测试(旧版)
│   └── debug-api-response.ts # API响应调试(旧版)
├── doc/                   # 文档目录
│   └── prd.md             # 产品需求文档
├── dist/                  # 构建输出目录
├── package.json           # 项目配置
├── tsconfig.json          # TypeScript配置
├── jest.config.js         # Jest测试配置
├── eslint.config.js       # ESLint代码规范配置
└── README.md              # 项目说明文档

数据表结构

SDK 操作的目标飞书多维表格包含以下字段:

| 字段名 | 字段类型 | 描述 | | :------- | :----------- | :--------------------------------- | | id | (记录ID) | 飞书系统自动生成的唯一记录 ID | | 提示词 | 文本 (Text) | 用户创建的 Prompt 内容 | | 作者 | 文本 (Text) | 创建该记录的用户的唯一标识符 (userId) | | 日期 | 数字 (Number) | 记录创建或更新的 Unix 时间戳(秒) |

使用示例

运行演示程序

1. 简单演示(应用级认证)

node examples/simple-demo.js

2. 手动OAuth演示(开发测试)

node examples/manual-oauth-demo.js

3. 完整OAuth演示

node examples/oauth-demo.js

配置管理

SDK提供了 ConfigManager 类来统一管理配置:

import { ConfigManager } from 'feishu-bitable-sdk';

// 获取飞书应用配置
const feishuConfig = ConfigManager.getFeishuConfig();

// 获取OAuth配置
const oauthConfig = ConfigManager.getOAuthConfig();

// 获取Bitable配置
const bitableConfig = ConfigManager.getBitableConfig();

// 验证配置完整性
ConfigManager.validateConfig();

// 验证OAuth配置
ConfigManager.validateOAuthConfig();

应用级认证示例

import { BitableSDK, ConfigManager } from 'feishu-bitable-sdk';

// 验证配置
ConfigManager.validateConfig();

// 获取配置
const config = ConfigManager.getFeishuConfig();

// 创建SDK实例
const sdk = new BitableSDK(config);

// 创建记录
const record = await sdk.addRecord('你好,世界!', 'user_001');

// 查询记录
const records = await sdk.listRecords('user_001');

// 更新记录
const updated = await sdk.updateRecord(record.id, 'Hello, World!');

// 删除记录
const result = await sdk.deleteRecord(record.id);

OAuth用户认证示例

import { OAuthManager, UserBitableSDK, ConfigManager } from 'feishu-bitable-sdk';

// 验证OAuth配置
ConfigManager.validateOAuthConfig();

// 获取配置
const oauthConfig = ConfigManager.getOAuthConfig();
const bitableConfig = ConfigManager.getBitableConfig();

// 创建OAuth管理器
const oauthManager = new OAuthManager(oauthConfig);

// 生成授权URL
const authUrl = oauthManager.generateAuthUrl();

// 处理OAuth回调
const userAuth = await oauthManager.handleCallback(authorizationCode);

// 创建用户级SDK
const userSdk = UserBitableSDK.createWithOAuth(
  oauthConfig,
  bitableConfig.baseId,
  bitableConfig.tableId,
  userAuth
);

// 使用用户级SDK
const records = await userSdk.listUserRecords();
const newRecord = await userSdk.addUserRecord('用户创建的记录');

测试

运行测试

# 运行所有测试
npm test

# 运行完整测试套件(包含所有测试类型)
npm run test:all

# 运行特定类型的测试
npm run test:crud      # CRUD集成测试
npm run test:error     # 错误处理测试
npm run test:performance # 性能测试
npm run test:concurrent  # 并发测试
npm run test:unit      # 单元测试

# 运行测试并生成覆盖率报告
npm run test:coverage

# 监听模式运行测试
npm run test -- --watch

测试覆盖

测试类型

  1. 单元测试 (tests/BitableSDK.test.ts)

    • SDK核心功能测试
    • 参数验证测试
    • 配置验证测试
  2. CRUD集成测试 (tests/crud-integration.test.ts)

    • 完整的增删改查操作测试
    • 数据一致性测试
    • 边界值测试
    • 特殊字符和Unicode测试
  3. 错误处理测试 (tests/error-handling.test.ts)

    • 参数验证错误测试
    • 网络错误和超时测试
    • 并发错误处理测试
    • 错误恢复测试
  4. 性能测试 (tests/performance.test.ts)

    • 单次操作性能测试
    • 批量操作性能测试
    • 并发性能测试
    • 内存使用测试
    • 响应时间测试
    • 压力测试
  5. 并发测试 (tests/concurrent.test.ts)

    • 基础并发测试
    • 高并发压力测试
    • 混合并发操作测试
    • 并发限制测试
    • 长时间并发测试
    • 并发性能基准测试

测试特性

  • 自动化清理:所有测试都会自动清理测试数据
  • 环境变量支持:支持通过 .env 文件配置测试环境
  • 详细日志:提供详细的测试执行日志和性能指标
  • 错误处理:完善的错误处理和恢复机制
  • 性能监控:实时监控测试性能和响应时间

贡献指南

  1. Fork 项目
  2. 创建功能分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request

开发规范

  • 使用 TypeScript 编写代码
  • 添加完整的 JSDoc 注释
  • 编写对应的单元测试
  • 遵循项目的代码风格

许可证

MIT License

更新日志

v1.2.0 (2024-01-XX)

  • 🔐 新增OAuth 2.0用户认证功能
    • OAuth认证管理器:完整的OAuth流程实现
    • 用户认证管理器:用户访问令牌管理
    • 用户级API管理器:基于用户认证的API调用
    • 用户级SDK:支持用户级CRUD操作
  • 📚 新增OAuth相关文档和示例
    • OAuth流程说明和配置指南
    • Web服务器集成示例
    • 完整的OAuth演示程序
  • 🔧 扩展类型定义和错误处理
    • 新增OAuth相关接口类型
    • 完善用户认证错误处理
    • 支持令牌刷新和验证

v1.1.0 (2024-01-XX)

  • 🧪 新增完整的测试套件
    • CRUD集成测试:完整的增删改查操作测试
    • 错误处理测试:各种异常场景和边界情况测试
    • 性能测试:单次、批量、并发操作性能测试
    • 并发测试:高并发场景下的稳定性测试
  • 🔧 新增测试工具和配置
    • 统一的测试配置管理
    • 自动化数据清理工具
    • 性能测量工具
    • 测试运行脚本
  • 📚 完善测试文档和使用说明

v1.0.0 (2024-01-XX)

  • 🎉 初始版本发布
  • ✨ 实现完整的CRUD操作
  • 🔐 自动化认证管理
  • 📝 完整的TypeScript类型定义
  • 🧪 基础单元测试
  • 📚 详细的使用文档和示例

技术支持

如果您在使用过程中遇到问题,请:

  1. 查看 文档
  2. 运行 示例程序
  3. 运行 OAuth演示程序
  4. 检查 测试用例
  5. 提交 Issue

相关链接