@gobing-ai/ts-utils (英语)
共享的公用设备——出错类型,日期帮助器,以光标为基础的页码,以角色为基础的访问控制,API响应构建器,以及输出格式化. 没有平台依赖性;在Bun,Node,和Cloudflare工人工作.
概览
ts-utils 提供小型、可堆肥的公用事业 ts-runtime, (中文(简体) ), ts-db, (中文(简体) ), ts-infra,和应用程序代码。 每个模块都是自成一体的,没有外部依赖性.
| 模块 | 目的 |
|---|---|
errors | 输入的应用程序出错( E)AppError, (中文(简体) ), NotFoundError, (中文(简体) ), ValidationError页:1 |
date | nowMs(),时间戳 #% 日期转换 |
cursor | 以光标为基础的 Base64url- 编码光标 |
access | Zitadel + 通用角色访问控制(hasRole, (中文(简体) ), getRoles(中文(简体) ) |
api-response | 标准 API 响应信封构建器 |
output | 人可读输出辅助器(表、JSON等) |
origin | 请求来源解析 |
const | 共享常数 |
建筑
classDiagram
class AppError {
+ErrorCode code
+string message
}
class NotFoundError {
}
class ValidationError {
}
class ConflictError {
}
class InternalError {
+unknown cause?
}
class ErrorCode {
<<enumeration>>
NotFound
Validation
Conflict
Internal
}
class CursorData {
<<interface>>
+string id
+number createdAt?
+number offset?
}
class CursorHelpers {
+createCursor(id, createdAt?, offset?) CursorData
+parseCursor(data) CursorData
+encodeCursor(cursor) string
+decodeCursor(encoded) string
+encodeCursorFromItem(id, createdAt?, offset?) string
+decodeAndParseCursor(encoded) CursorData
+buildCursorMeta(items, limit, hasMore) object
}
class DateHelpers {
+nowMs() number
+toMs(input) number | null
+fromMs(ms) Date | null
}
class AccessControl {
+hasRole(profile, role) boolean
+getRoles(profile) string[]
}
AppError <|-- NotFoundError
AppError <|-- ValidationError
AppError <|-- ConflictError
AppError <|-- InternalError
AppError --> ErrorCode
如何运作
错误类型
带有出错代码的已打出错误等级——消费者按类型而不是字符串抓取 :
throw new NotFoundError(`User ${userId} not found`);
throw new ValidationError('Email is required');
throw new InternalError('DB connection lost', originalError);
// Callers can discriminate:
if (error instanceof NotFoundError) {
return new Response(null, { status: 404 });
}
if (isAppError(error)) {
// error.code is typed: 'NOT_FOUND' | 'VALIDATION' | 'CONFLICT' | 'INTERNAL'
}
基于光标的平面
从页面中最后一个项目编码光标, 返回客户端, 在下一个请求中解码 :
import { encodeCursorFromItem, decodeAndParseCursor } from '@gobing-ai/ts-utils';
// Page 1: encode cursor from last item
const cursor = encodeCursorFromItem(lastItem.id, lastItem.createdAt);
// → "eyJpZCI6ImFiYyIsImNyZWF0ZWRBdCI6MTcwMDAwMDAwMH0"
// Page 2: decode cursor from query param
const parsed = decodeAndParseCursor(requestCursor);
// → { id: "abc", createdAt: 1700000000 }
// Build pagination metadata
const meta = buildCursorMeta(items, limit, hasMore);
// → { nextCursor: "eyJ...", hasMore: true, limit: 20 }
光标流量 :
sequenceDiagram
Client->>API: GET /items?limit=20
API->>DB: SELECT ... LIMIT 20
DB-->>API: 20 rows
API->>API: encodeCursorFromItem(lastItem)
API-->>Client: { items: [...], nextCursor: "eyJ..." }
Client->>API: GET /items?limit=20&cursor=eyJ...
API->>API: decodeAndParseCursor("eyJ...")
API->>DB: SELECT ... WHERE id > "abc" LIMIT 20
DB-->>API: 20 rows
API-->>Client: { items: [...], nextCursor: "..." }
基于角色的出入控制
支持 Zitadel IAM 角色和通用角色阵列/对象:
import { hasRole, getRoles } from '@gobing-ai/ts-utils';
// Zitadel profile
const profile = {
'urn:zitadel:iam:org:project:roles': { admin: 'project-1', viewer: 'project-1' },
};
hasRole(profile, 'admin'); // → true
getRoles(profile); // → ['admin', 'viewer']
// Generic roles array
hasRole({ roles: ['editor', 'viewer'] }, 'editor'); // → true
// Object-based roles
hasRole({ roles: { admin: true } }, 'admin'); // → true
日期公用事业
import { nowMs, toMs, fromMs } from '@gobing-ai/ts-utils';
const ts = nowMs(); // → 1700000000000
toMs(new Date('2024-01-01')); // → 1704067200000
toMs('2024-01-01'); // → 1704067200000
toMs(null); // → null
fromMs(1704067200000); // → Date('2024-01-01')
fromMs(null); // → null
使用量
安装
bun add @gobing-ai/ts-utils
共同模式
import {
AppError, NotFoundError, ValidationError, ConflictError, InternalError,
nowMs, toMs, fromMs,
encodeCursorFromItem, decodeAndParseCursor, buildCursorMeta,
hasRole, getRoles,
} from '@gobing-ai/ts-utils';
// Errors
function getUser(id: string) {
const user = db.find(id);
if (!user) throw new NotFoundError(`User ${id} not found`);
return user;
}
// Pagination
async function listUsers(limit: number, cursor?: string) {
const parsed = cursor ? decodeAndParseCursor(cursor) : undefined;
const users = await db.query(limit, parsed?.id);
const hasMore = users.length === limit;
return {
items: users,
...buildCursorMeta(users, limit, hasMore),
};
}
// Auth guard
function requireAdmin(profile: unknown) {
if (!hasRole(profile as Record<string, unknown>, 'admin')) {
throw new ForbiddenError('Admin access required');
}
}