@be-link/shield-for-tcb-node-sdk
v1.0.24
Published
ShieldForTCB Node.js SDK
Readme
ShieldForTCB SDK
ShieldForTCB Node.js SDK - 敏感信息管理服务客户端
安装
npm install @be-link/shield-for-tcb-node-sdk
# 或
pnpm add @be-link/shield-for-tcb-node-sdkV2 SDK(推荐)
V2 SDK 从 MySQL 数据源读取配置,支持按 service + key 获取配置,并提供自动类型解析。
基本使用
import { backendConfigServiceV2 } from '@be-link/shield-for-tcb-node-sdk'获取服务列表
const services = await backendConfigServiceV2.getServices('local')
// 返回: ['BackendUser', 'Trade', 'User', ...]获取服务的配置键列表
const keys = await backendConfigServiceV2.getServiceKeys('TestService', 'local')
// 返回: ['TestServiceKey1', 'TestServiceKey2', 'TestServiceKey3', ...]获取单个配置
// 原始格式(包含元数据)
const config = await backendConfigServiceV2.fetchConfig({
service: 'TestService',
key: 'TestServiceKey1',
env: 'local'
})
// 返回: { config_key: 'TestServiceKey1', value: 'xxx', value_type: 'string', updated_at: '...' }
// 自动解析类型(推荐)
const host = await backendConfigServiceV2.getConfigValue<string>('TestService', 'TestServiceKey1', 'local')
// 返回: '127.0.0.1'
const port = await backendConfigServiceV2.getConfigValue<number>('TestService', 'TestServiceKey1', 'local')
// 返回: 1234(自动解析为数字)
const enabled = await backendConfigServiceV2.getConfigValue<boolean>('TestService', 'TestServiceKey1', 'local')
// 返回: true/false(自动解析为布尔值)
const jsonConfig = await backendConfigServiceV2.getConfigValue<object>('BackendUser', 'TestServiceKey1', 'local')
// 返回: { ... }(自动 JSON 解析)批量获取配置
// 原始格式
const configs = await backendConfigServiceV2.fetchConfigs({
service: 'TestService',
keys: ['TestServiceKey1', 'TestServiceKey2'],
env: 'local'
})
// 返回: { 'TestServiceKey1': { value: 'xxx', value_type: 'string' }, ... }
// 自动解析类型(推荐)
const values = await backendConfigServiceV2.getConfigValues(
'TestService',
['TestServiceKey1', 'TestServiceKey2', 'TestServiceKey3'],
'local'
)
// 返回: {
// }环境变量
| 变量名 | 说明 | 示例 |
|--------|------|------|
| SHIELD_SDK_HOST | 覆盖 SDK 请求地址(本地开发用) | http://localhost:8090 |
| CONTAINER_ENV | 容器环境,默认 SCF(云函数),设置为其他值使用内网地址 | ECS |
| NODE_ENV | 环境标识,prod 使用生产环境地址 | local / ppe / prod |
本地开发
# 设置本地服务地址
export SHIELD_SDK_HOST=http://localhost:8090V1 SDK(旧版)
V1 SDK 从 YAML 文件读取配置,保持向后兼容。
import { backendConfigService, frontendConfigService } from '@be-link/shield-for-tcb-node-sdk'
// 服务端使用(默认,包含异常处理)
const config = await backendConfigService.fetchConfig({ key: 'your-key', type: 'json' })
// 前端使用(跳过异常处理,直接抛出原始错误)
const frontendConfig = await frontendConfigService.fetchConfig({ key: 'your-key', type: 'json' })
V1 vs V2 对比
| 特性 | V1 SDK | V2 SDK | |------|--------|--------| | 数据源 | YAML 文件 | MySQL | | 获取方式 | 按 key | 按 service + key | | 类型解析 | 手动指定 type | 自动根据 value_type 解析 | | 批量获取 | ❌ | ✅ | | 配置管理 | ❌ | ✅(通过管理后台) | | 版本追踪 | ❌ | ✅ | | 审计日志 | ❌ | ✅ |
ShieldConfigManager(配置管理器)
ShieldConfigManager 提供配置自动拉取、缓存、定时刷新功能,适合需要持续使用配置的服务。
使用方式
import { ShieldConfigManager } from '@be-link/shield-for-tcb-node-sdk'
const manager = new ShieldConfigManager({
serviceName: 'BackendBff',
env: 'local',
enableInfoLog: true, // 可选,默认 false
})
await manager.setup()
const config = manager.getConfig<MyConfig>()
manager.stop()配置参数
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| serviceName | string | 必填 | 服务名称 |
| env | string | NODE_ENV | 环境 |
| refreshIntervalMs | number | 5000 | 刷新间隔(毫秒) |
| fetchTimeoutMs | number | 10000 | 请求超时(毫秒) |
| enableInfoLog | boolean | false | 是否打印 info 日志 |
| logger | Logger | console | 自定义日志函数 |
日志说明
enableInfoLog 默认为 false,不打印 info 级别日志。设置为 true 时会打印以下日志:
- 初始化成功
- 配置刷新(包含配置的 key 列表)
- 配置最终内容
- 定时器启动信息
- 停止信息
error 级别日志不受 enableInfoLog 影响,始终打印:
- 初始刷新失败
- 配置为空警告
- 刷新错误
- 定时器刷新错误
API
| 方法 | 说明 |
|------|------|
| setup() | 初始化并启动定时刷新,幂等操作 |
| getConfig<T>() | 获取类型化的配置对象 |
| getValue<T>(key, defaultValue?) | 根据 key 获取配置值,支持默认值 |
| isSwitchEnabled(key, defaultValue?) | 获取布尔开关状态 |
| isHitGrey(configKey, identifier, defaultValue?) | 判断是否命中灰度流量 |
| refresh() | 手动触发一次配置刷新 |
| stop() | 停止定时刷新,清理资源 |
| waitForSetup() | 等待初始化完成 |
| isSetup | 是否已完成初始化(只读属性) |
| config | 当前缓存的配置(原始 Record,只读属性) |
获取配置值
// 获取配置(带默认值)
const port = manager.getValue('API_PORT', 8090)
// 获取配置并指定类型
const isEnabled = manager.getValue<boolean>('FEATURE.ENABLED', false)开关状态检查
// 检查功能是否开启(支持 true/false, 1/0, yes/no, on/off 等多种格式)
const isEnabled = manager.isSwitchEnabled('FEATURE.ENABLED')
// 指定默认值为 true
const isDebug = manager.isSwitchEnabled('DEBUG_MODE', true)灰度流量控制
// 流量控制配置结构
interface TrafficControlConfig {
enabled: boolean // 总开关
totalBuckets: number // 总桶数
effectiveBuckets: number // 生效桶数(0 到 effectiveBuckets-1 生效)
whitelist?: string[] // 白名单(命中后视为生效)
blacklist?: string[] // 黑名单(命中后视为不生效)
}
// 判断用户是否命中灰度流量
const isHit = manager.isHitGrey('TRAFFIC_SPLIT', userId, false)
if (isHit) {
// 灰度流量逻辑
}批量获取配置
// 原始格式
const configs = await backendConfigServiceV2.fetchConfigs({
service: 'TestService',
keys: ['TestServiceKey1', 'TestServiceKey2'],
env: 'local'
})
// 返回: { 'TestServiceKey1': { value: 'xxx', value_type: 'string' }, ... }
// 自动解析类型(推荐)
const values = await backendConfigServiceV2.getConfigValues(
'TestService',
['TestServiceKey1', 'TestServiceKey2', 'TestServiceKey3'],
'local'
)
// 返回: {
// 'TestServiceKey1': 'xxx',
// 'TestServiceKey2': 123,
// 'TestServiceKey3': true
// }云函数场景:按单 Key 读取配置
云函数等短生命周期场景不适合在每次请求中初始化 ShieldConfigManager 并拉取全量配置。可以使用 ShieldCloudFunctionConfig 按需读取单个 key:构造不发请求、不 setup()、不启动定时器、SDK 侧不维护本地缓存,每次 fetchKey() 只发一次单 key HTTP 请求,缓存集中在 Shield 服务端(本地内存 + Redis + MySQL)。
import { ShieldCloudFunctionConfig } from '@be-link/shield-for-tcb-node-sdk'
const configClient = new ShieldCloudFunctionConfig({
serviceName: 'TheVitality',
env: 'prod',
fetchTimeoutMs: 2000,
})
export async function handler() {
const redisConfig = await configClient.fetchKey<{
HOST: string
PORT: number
}>('REDIS')
const timeout = await configClient.fetchKey<number>('API_TIMEOUT', 3000)
const enabled = await configClient.isSwitchEnabled('FEATURE_ENABLED', false)
const isHit = await configClient.isHitGrey('TRAFFIC_SPLIT', 'user_001', false)
return { redisConfig, timeout, enabled, isHit }
}行为说明
- 构造
ShieldCloudFunctionConfig不会发起 HTTP 请求。 - 不需要调用
setup()。 - 不会启动定时器。
- SDK 侧不维护本地缓存。
- 每次
fetchKey()都会请求 Shield 服务端单 key 接口POST /shield/v2/config/cloud-function/fetch-key。 - 默认超时时间为 2 秒,可以通过
fetchTimeoutMs覆盖。 - 配置不存在、HTTP 超时、网络异常、Shield 5xx 时,
fetchKey()返回defaultValue或undefined。 defaultValue同时适用于「配置不存在」和「远程读取失败」,安全敏感开关应选择 fail-safe 默认值。- 多个 key 会产生多次 HTTP 请求;如果同一次云函数调用需要多个 key,调用方应评估延迟预算。
isSwitchEnabled()/isHitGrey()与ShieldConfigManager保持一致的解析与灰度规则,灰度判断复用同一套逻辑,结果不会漂移。
发布流程
自动发布(推荐)
使用发布脚本,会自动完成版本更新、构建和发布:
# 在 SDK 目录下执行
cd packages/sdk
pnpm publish
# 或在根目录执行
pnpm publish:sdk发布脚本会自动:
- 设置 npm 配置和认证(需要
NPM_DEPLOY_TOKEN环境变量) - 更新版本号(使用
npm version patch,只读模式) - 构建项目
- 发布到 npm(使用
pnpm publish --no-git-checks,只读文件发布) - 发送飞书通知(需要
FEISHU_WEBHOOK_URL环境变量)
环境变量
发布脚本需要以下环境变量(可选):
NPM_DEPLOY_TOKEN: npm 发布 tokenFEISHU_WEBHOOK_URL: 飞书 webhook URL(用于发送发布通知)
CI/CD 集成
在 Jenkins 或其他 CI/CD 平台中,可以这样使用:
export NPM_DEPLOY_TOKEN="your-token"
export FEISHU_WEBHOOK_URL="https://open.feishu.cn/open-apis/bot/v2/hook/xxx"
cd packages/sdk
pnpm publish手动发布
如果需要手动发布:
# 1. 构建
pnpm build
# 2. 进入 dist 目录发布(只读文件发布)
cd dist
pnpm publish --no-git-checks --access public
cd ..License
ISC
