API 参考已发布
RailWise TypeScript SDK 文档
RailWise TypeScript SDK 的安装配置、核心 API、类型定义、使用示例及最佳实践
API 参考
RailWise TypeScript SDK 文档
Section titled “RailWise TypeScript SDK 文档”1. SDK 概述
Section titled “1. SDK 概述”RailWise TypeScript SDK(@railwise/sdk)是官方提供的 TypeScript/JavaScript 客户端库,用于与 RailWise API 服务进行交互。SDK 提供了完整的类型定义、请求封装和错误处理,适用于 Node.js 和浏览器环境。
1.1 核心特性
Section titled “1.1 核心特性”| 特性 | 说明 |
|---|---|
| 完整类型支持 | 所有 API 请求和响应均提供 TypeScript 类型定义 |
| Promise 异步 | 基于 Promise 的异步 API,支持 async/await |
| 自动重试 | 内置指数退避重试机制 |
| 请求拦截 | 支持自定义请求和响应拦截器 |
| 错误处理 | 统一的错误类型和详细的错误信息 |
| 浏览器兼容 | 支持现代浏览器和 Node.js 环境 |
| ESM/CJS 双模式 | 同时支持 ES Module 和 CommonJS |
1.2 技术栈
Section titled “1.2 技术栈”- 语言:TypeScript 5.0+
- 运行时:Node.js 18+ / 现代浏览器
- HTTP 客户端:原生 fetch(Node.js 18+)/ 可配置自定义客户端
- 打包:Rollup + TypeScript
2.1 npm 安装
Section titled “2.1 npm 安装”# 使用 npmnpm install @railwise/sdk
# 使用 yarnyarn add @railwise/sdk
# 使用 pnpmpnpm add @railwise/sdk
# 使用 bunbun add @railwise/sdk2.2 版本要求
Section titled “2.2 版本要求”| 依赖 | 最低版本 | 说明 |
|---|---|---|
| Node.js | 18.0.0 | 运行时环境 |
| TypeScript | 5.0.0 | 类型系统(开发依赖) |
2.3 版本更新
Section titled “2.3 版本更新”# 检查当前版本npm list @railwise/sdk
# 更新到最新版本npm update @railwise/sdk
# 安装特定版本npm install @railwise/sdk@1.2.03. 快速开始
Section titled “3. 快速开始”3.1 初始化客户端
Section titled “3.1 初始化客户端”import { RailWiseClient } from '@railwise/sdk';
// 使用 API Key 初始化const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx', baseURL: 'https://api.railwise.cn/v1', // 可选,默认为生产环境 timeout: 30000, // 可选,默认 30000ms maxRetries: 3, // 可选,默认 3 次});3.2 环境变量配置
Section titled “3.2 环境变量配置”import { RailWiseClient } from '@railwise/sdk';
// 从环境变量读取配置const client = new RailWiseClient({ apiKey: process.env.RAILWISE_API_KEY!, baseURL: process.env.RAILWISE_API_URL,});3.3 第一个请求
Section titled “3.3 第一个请求”import { RailWiseClient } from '@railwise/sdk';
async function main() { const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx', });
try { // 查询项目列表 const projects = await client.projects.list({ status: 'active', limit: 10, });
console.log(`找到 ${projects.total} 个活跃项目`);
for (const project of projects.items) { console.log(`- ${project.projectName} (${project.projectId})`); } } catch (error) { console.error('请求失败:', error); }}
main();4. 核心 API
Section titled “4. 核心 API”4.1 项目 API(Projects)
Section titled “4.1 项目 API(Projects)”const projects = await client.projects.list({ status: 'active', // 'active' | 'paused' | 'completed' | 'all' limit: 50, // 1-200 offset: 0, // 分页偏移});
// 返回类型:ListProjectsResponseinterface ListProjectsResponse { total: number; items: Project[]; hasMore: boolean;}获取项目详情
Section titled “获取项目详情”const project = await client.projects.get('PRJ-A1B2C3D4', { includePoints: true, // 包含测点信息 includeDevices: false, // 包含设备信息});
// 返回类型:ProjectDetailinterface ProjectDetail { projectId: string; projectName: string; projectType: 'subway_protection' | 'building' | 'slope' | 'tunnel'; status: 'active' | 'paused' | 'completed'; location: { province: string; city: string; district: string; }; points?: MonitoringPoint[]; devices?: Device[];}4.2 监测数据 API(Monitoring Data)
Section titled “4.2 监测数据 API(Monitoring Data)”查询监测数据
Section titled “查询监测数据”import { DataType, AggregationType } from '@railwise/sdk';
const data = await client.monitoringData.query({ projectId: 'PRJ-A1B2C3D4', pointIds: ['PT-001', 'PT-002'], // 可选,为空查询所有测点 dataType: DataType.Settlement, // 'settlement' | 'displacement' | 'convergence' | 'stress' | 'all' startTime: new Date('2025-01-14T00:00:00Z'), endTime: new Date('2025-01-15T23:59:59Z'), aggregation: AggregationType.Hourly, // 'raw' | 'hourly' | 'daily' | 'weekly' limit: 1000,});
// 返回类型:MonitoringDataResponseinterface MonitoringDataResponse { projectId: string; dataType: DataType; timeRange: { start: Date; end: Date; }; totalRecords: number; points: MonitoringPointData[]; summary: { normalCount: number; yellowWarningCount: number; orangeWarningCount: number; redWarningCount: number; };}查询测量历史
Section titled “查询测量历史”const history = await client.monitoringData.getHistory({ pointId: 'PT-001', startTime: new Date('2025-01-01T00:00:00Z'), endTime: new Date('2025-01-15T23:59:59Z'), includeRaw: false, // 是否包含原始观测数据});4.3 设备 API(Devices)
Section titled “4.3 设备 API(Devices)”查询设备状态
Section titled “查询设备状态”const devices = await client.devices.list({ projectId: 'PRJ-A1B2C3D4', // 可选 deviceIds: ['DEV-TS-001'], // 可选});
// 返回类型:DeviceListResponseinterface DeviceListResponse { devices: Device[]; summary: { total: number; online: number; offline: number; warning: number; };}4.4 计算 API(Compute)
Section titled “4.4 计算 API(Compute)”import { CoordinateSystem, TransformMethod } from '@railwise/sdk';
const result = await client.compute.coordinateTransform({ coordinates: [ { x: 384567.123, y: 3156784.456, z: 12.345 }, { x: 384568.456, y: 3156785.789, z: 12.456 }, ], sourceCRS: CoordinateSystem.CGCS2000, targetCRS: CoordinateSystem.Local, transformMethod: TransformMethod.SevenParameter, // 可选:自定义转换参数 transformParams: { dx: 100.0, dy: 200.0, dz: 0.0, rx: 0.0, ry: 0.0, rz: 0.0, scale: 1.0, },});
// 返回类型:CoordinateTransformResultinterface CoordinateTransformResult { transformId: string; sourceCRS: CoordinateSystem; targetCRS: CoordinateSystem; results: TransformedCoordinate[]; statistics: { pointCount: number; maxResidual: number; rms: number; };}import { AdjustmentType, ObservationType, UnknownType } from '@railwise/sdk';
const result = await client.compute.adjustment({ adjustmentType: AdjustmentType.Indirect, observations: [ { obsId: 'OBS-001', obsType: ObservationType.Distance, value: 100.523, precision: 0.002, }, { obsId: 'OBS-002', obsType: ObservationType.Angle, value: 89.5234, precision: 0.001, }, ], unknowns: [ { unknownId: 'X1', unknownType: UnknownType.Coordinate, approximateValue: 1000.0, }, ],});import { AnalysisType } from '@railwise/sdk';
const analysis = await client.compute.deformationAnalysis({ pointId: 'PT-001', analysisType: AnalysisType.Comprehensive, startTime: new Date('2024-06-01T00:00:00Z'), endTime: new Date('2025-01-15T23:59:59Z'), forecastDays: 7, // 预测天数});
// 返回类型:DeformationAnalysisResultinterface DeformationAnalysisResult { pointId: string; analysisType: AnalysisType; cumulativeDeformation: { maxValue: number; minValue: number; currentValue: number; unit: string; }; deformationRate: { currentRate: number; averageRate: number; maxRate: number; }; trend: { direction: 'settling' | 'rising' | 'stable'; stability: 'stable' | 'unstable'; confidence: number; }; forecast?: { forecastDays: number; predictedValue: number; confidenceInterval: { lower: number; upper: number; }; }; warningAssessment: { currentLevel: 'normal' | 'yellow' | 'orange' | 'red'; trendLevel: 'normal' | 'yellow' | 'orange' | 'red'; recommendation: string; };}5. 高级配置
Section titled “5. 高级配置”5.1 自定义 HTTP 客户端
Section titled “5.1 自定义 HTTP 客户端”import { RailWiseClient } from '@railwise/sdk';
const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx', // 自定义 fetch 实现 fetch: customFetch, // 或自定义 axios 实例 httpClient: axiosInstance,});5.2 请求拦截器
Section titled “5.2 请求拦截器”const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx',});
// 请求拦截client.interceptors.request.use((config) => { console.log(`发送请求: ${config.method} ${config.url}`); // 添加自定义请求头 config.headers['X-Request-ID'] = generateRequestId(); return config;});
// 响应拦截client.interceptors.response.use( (response) => { console.log(`请求成功: ${response.status}`); return response; }, (error) => { console.error(`请求失败: ${error.message}`); return Promise.reject(error); });5.3 重试配置
Section titled “5.3 重试配置”const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx', maxRetries: 5, retryDelay: 1000, // 初始重试延迟(毫秒) retryMultiplier: 2, // 指数退避乘数 retryMaxDelay: 30000, // 最大重试延迟 // 自定义重试条件 retryCondition: (error) => { // 仅对 5xx 错误和超时进行重试 return error.status >= 500 || error.code === 'ETIMEDOUT'; },});6. 错误处理
Section titled “6. 错误处理”6.1 错误类型
Section titled “6.1 错误类型”import { RailWiseError, AuthenticationError, PermissionError, NotFoundError, ValidationError, RateLimitError, ServerError,} from '@railwise/sdk';
try { const data = await client.monitoringData.query({...});} catch (error) { if (error instanceof AuthenticationError) { console.error('认证失败,请检查 API Key'); } else if (error instanceof PermissionError) { console.error('权限不足,请检查 API Key 权限范围'); } else if (error instanceof NotFoundError) { console.error('资源不存在,请检查项目ID或测点ID'); } else if (error instanceof ValidationError) { console.error('请求参数错误:', error.details); } else if (error instanceof RateLimitError) { console.error('请求过于频繁,请稍后重试'); console.log(`配额重置时间: ${error.retryAfter}`); } else if (error instanceof ServerError) { console.error('服务器错误,请稍后重试'); } else { console.error('未知错误:', error); }}6.2 错误类型定义
Section titled “6.2 错误类型定义”class RailWiseError extends Error { code: string; status: number; requestId: string; details?: Record<string, unknown>;}
class AuthenticationError extends RailWiseError { status = 401;}
class PermissionError extends RailWiseError { status = 403;}
class NotFoundError extends RailWiseError { status = 404;}
class ValidationError extends RailWiseError { status = 400; details: ValidationDetail[];}
class RateLimitError extends RailWiseError { status = 429; retryAfter: number; // 秒 limit: number; remaining: number; resetTime: Date;}
class ServerError extends RailWiseError { status = 500;}7. 完整示例
Section titled “7. 完整示例”7.1 监测数据批量导出
Section titled “7.1 监测数据批量导出”import { RailWiseClient, DataType, AggregationType } from '@railwise/sdk';import { writeFileSync } from 'fs';
async function exportMonitoringData( projectId: string, startDate: Date, endDate: Date, outputPath: string) { const client = new RailWiseClient({ apiKey: process.env.RAILWISE_API_KEY!, });
// 查询项目信息 const project = await client.projects.get(projectId, { includePoints: true, });
console.log(`导出项目: ${project.projectName}`); console.log(`测点数量: ${project.points?.length || 0}`);
// 查询监测数据 const data = await client.monitoringData.query({ projectId, dataType: DataType.All, startTime: startDate, endTime: endDate, aggregation: AggregationType.Daily, });
// 转换为 CSV 格式 const csv = convertToCSV(data); writeFileSync(outputPath, csv);
console.log(`数据已导出到: ${outputPath}`); console.log(`总记录数: ${data.totalRecords}`); console.log(`预警统计:`, data.summary);}
function convertToCSV(data: MonitoringDataResponse): string { const headers = ['timestamp', 'pointId', 'pointName', 'value', 'unit', 'changeRate', 'warningLevel']; const rows = data.points.flatMap(point => point.records.map(record => [ record.timestamp.toISOString(), point.pointId, point.pointName, record.value, record.unit, record.changeRate, record.warningLevel, ]) );
return [headers.join(','), ...rows.map(row => row.join(','))].join('\n');}
// 使用示例exportMonitoringData( 'PRJ-A1B2C3D4', new Date('2025-01-01T00:00:00Z'), new Date('2025-01-15T23:59:59Z'), './monitoring-data.csv');7.2 自动化预警检查
Section titled “7.2 自动化预警检查”import { RailWiseClient, DataType, AnalysisType } from '@railwise/sdk';
async function checkWarnings(projectId: string) { const client = new RailWiseClient({ apiKey: process.env.RAILWISE_API_KEY!, });
// 查询最近 24 小时数据 const endTime = new Date(); const startTime = new Date(endTime.getTime() - 24 * 60 * 60 * 1000);
const data = await client.monitoringData.query({ projectId, dataType: DataType.Settlement, startTime, endTime, });
// 筛选预警测点 const warningPoints = data.points.filter(point => point.records.some(r => r.warningLevel !== 'normal') );
if (warningPoints.length === 0) { console.log('✅ 所有测点正常'); return; }
console.log(`⚠️ 发现 ${warningPoints.length} 个预警测点:`);
for (const point of warningPoints) { const latestRecord = point.records[point.records.length - 1];
// 执行变形分析 const analysis = await client.compute.deformationAnalysis({ pointId: point.pointId, analysisType: AnalysisType.Comprehensive, startTime: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), endTime, });
console.log(`\n测点: ${point.pointName} (${point.pointId})`); console.log(` 当前值: ${latestRecord.value} ${latestRecord.unit}`); console.log(` 预警级别: ${latestRecord.warningLevel}`); console.log(` 变化速率: ${analysis.deformationRate.currentRate} mm/天`); console.log(` 建议: ${analysis.warningAssessment.recommendation}`); }}
// 定时执行setInterval(() => { checkWarnings('PRJ-A1B2C3D4').catch(console.error);}, 4 * 60 * 60 * 1000); // 每 4 小时检查一次8. 类型导出
Section titled “8. 类型导出”SDK 导出所有类型定义,便于在项目中使用:
import type { // 项目类型 Project, ProjectDetail, ProjectStatus, ProjectType,
// 测点类型 MonitoringPoint, MonitoringPointData, PointRecord,
// 设备类型 Device, DeviceStatus, DeviceType,
// 数据类型 DataType, AggregationType, WarningLevel, MonitoringDataResponse,
// 计算类型 CoordinateSystem, TransformMethod, AdjustmentType, AnalysisType,
// 错误类型 RailWiseError, AuthenticationError, // ...} from '@railwise/sdk';9. 浏览器使用
Section titled “9. 浏览器使用”SDK 支持在浏览器环境中使用(需配置 CORS):
// 浏览器环境import { RailWiseClient } from '@railwise/sdk';
const client = new RailWiseClient({ apiKey: 'rw_live_xxxxxxxxxxxxxxxx', // 浏览器环境需要配置代理或允许 CORS 的端点 baseURL: 'https://your-proxy-server.com/railwise-api',});
// 在 React 组件中使用function MonitoringDashboard() { const [data, setData] = useState<MonitoringDataResponse | null>(null);
useEffect(() => { client.monitoringData.query({ projectId: 'PRJ-A1B2C3D4', dataType: DataType.Settlement, startTime: new Date(Date.now() - 24 * 60 * 60 * 1000), endTime: new Date(), }).then(setData); }, []);
return ( <div> {data && ( <div> <h2>监测数据概览</h2> <p>总测点数: {data.totalRecords}</p> <p>正常: {data.summary.normalCount}</p> <p>预警: {data.summary.yellowWarningCount + data.summary.orangeWarningCount}</p> </div> )} </div> );}10. 相关文档
Section titled “10. 相关文档”- Python SDK — Python 客户端库文档
- MCP Server 概述 — MCP Server 功能介绍
- MCP Server 安装配置 — MCP Server 安装步骤
- MCP Server 工具列表 — 完整的工具清单
本文档由 RailWise 技术文档团队维护,最后更新于 2025-01-15。
