@stago/sdk
v2.1.7
Published
云台模块开发 SDK,为非专业开发人员提供简化的模块配置和 API 开发工具。
Readme
@stago/sdk
云台模块开发 SDK,为非专业开发人员提供简化的模块配置和 API 开发工具。
安装
pnpm add @stago/sdk功能模块
1. 模块配置 (defineModule)
简化模块配置,SDK 自动处理 Module Federation 内部细节:
// stago.config.ts
import { defineModule } from '@stago/sdk'
export default defineModule({
name: '@demo/task-management',
version: '1.0.0',
description: '任务管理模块',
menu: {
title: '任务管理',
icon: 'UnorderedListOutlined',
order: 10,
children: [
{ key: 'dashboard', title: '仪表盘', path: '/' },
{ key: 'list', title: '任务列表', path: '/list' }
]
},
api: {
prefix: '/tasks',
handlers: './src/api'
}
})2. 模块上下文 Hooks
在 React 组件中使用平台提供的上下文:
import { useModule, useUser, useRouter } from '@stago/sdk'
function MyComponent() {
// 获取完整上下文
const { user, theme, router, notifications, platform } = useModule()
// 或使用便捷 hooks
const user = useUser()
const router = useRouter()
const http = useHttp()
const storage = useStorage()
// 使用 HTTP 客户端
const data = await http.get('/api/tasks')
// 使用路由导航
router.navigate('/detail/123')
return <div>{user.displayName}</div>
}3. API SDK (defineApiRouter)
为模块定义后端 API 路由(使用 Hono 框架):
// src/api/index.ts
import { defineApiRouter, apiSuccess, apiError } from '@stago/sdk'
export default defineApiRouter({
prefix: '/employee',
routes: {
'/list': {
GET: async (c, ctx) => {
const result = await ctx.db.query('SELECT * FROM employees')
return apiSuccess(c, { employees: result.rows })
}
},
'/create': {
middleware: [
async (c, next) => {
const body = await c.req.json()
if (!body.name) {
return apiError(c, 'VALIDATION_ERROR', 'name is required', 400)
}
await next()
}
],
POST: async (c, ctx) => {
const { name, phone } = await c.req.json()
await ctx.db.query(
'INSERT INTO employees (name, phone) VALUES ($1, $2)',
[name, phone]
)
return apiSuccess(c, { created: true }, 'Employee created')
}
},
'/:id': {
GET: async (c, ctx) => {
const result = await ctx.db.query(
'SELECT * FROM employees WHERE id = $1',
[c.req.param('id')]
)
if (result.rows.length === 0) {
return apiError(c, 'NOT_FOUND', 'Employee not found', 404)
}
return apiSuccess(c, result.rows[0])
}
}
}
})4. API 响应工具
标准化 API 响应格式(Hono Context):
// 成功响应
return apiSuccess(c, { items: [...] }, 'Items fetched')
// => { success: true, data: { items: [...] }, message: 'Items fetched' }
// 错误响应
return apiError(c, 'NOT_FOUND', 'Item not found', 404)
// => { success: false, error: { code: 'NOT_FOUND', message: 'Item not found' } }
// 验证错误
return apiValidationError(c, ['name', 'email'])
// => { success: false, error: { code: 'VALIDATION_ERROR', message: '缺少必要参数: name, email' } }5. 生命周期钩子
模块加载/卸载时执行:
import { defineApiWithSetup } from '@stago/sdk'
let cache: Map<string, unknown>
export default defineApiWithSetup({
config: {
routes: {
'/list': {
GET: async (c, ctx) => {
const cached = cache.get('employees')
if (cached) return apiSuccess(c, cached)
const result = await ctx.db.query('SELECT * FROM employees')
cache.set('employees', result.rows)
return apiSuccess(c, { employees: result.rows })
}
}
}
},
setup: async (ctx) => {
cache = new Map()
ctx.log('info', 'Module initialized with cache')
},
teardown: () => {
cache.clear()
}
})API 上下文 (ApiContext)
每个 API handler 接收平台提供的上下文:
interface ApiContext {
db: {
query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[] }>
}
module: {
name: string // 模块名 @scope/name
version: string // 版本号
}
log: (level: 'info' | 'warn' | 'error', message: string, data?: unknown) => void
}模块上下文 (ModuleContext)
React 组件可用完整上下文:
interface ModuleContext {
user: ModuleUser // 用户信息
theme: ModuleTheme // 主题控制
router: ModuleRouter // 路由导航
notifications: ModuleNotifications // 通知服务
globalState: ModuleGlobalState // 跨模块状态
platform: PlatformServices // 平台服务
}类型导出
SDK 导出完整的 TypeScript 类型定义:
ModuleConfig- 模块配置ApiHandler- API 处理函数ApiContext- API 上下文RouteDefinition- 路由定义ModuleContext- 模块上下文ModuleUser- 用户信息- 等 20+ 类型
6. 开发环境数据库访问 (@stago/sdk/dev)
模块开发时,可在本地 Dev Server 直接访问真实数据库:
// .env 配置
DB_HOST=localhost
DB_PORT=5432
DB_NAME=your_database
DB_USER=postgres
DB_PASSWORD=your_password// vite.config.ts
import { stagoDevApiPlugin } from '@stago/sdk/dev-vite'
export default defineConfig({
plugins: [
react(),
stagoDevApiPlugin({ port: 3100 }) // 仅 dev 模式生效
]
})启动 pnpm dev 后:
- 前端:Vite Dev Server(默认 5001)
- API:独立 Hono Server(默认 3100)
测试 API:
curl http://localhost:3100/my-module/hello
curl http://localhost:3100/my-module/data开发时 ctx.db.query() 直接访问 .env 配置的真实数据库,无需 mock。
注意: @stago/sdk/dev 和 @stago/sdk/dev-vite 仅用于开发,不会打包到生产。
许可证
MIT
