跳转到内容
API 参考已发布

RailWise TypeScript SDK 文档

RailWise TypeScript SDK 的安装配置、核心 API、类型定义、使用示例及最佳实践

复核 2026-07-09入门公开可引用RailWise 技术团队
API 参考

RailWise TypeScript SDK(@railwise/sdk)是官方提供的 TypeScript/JavaScript 客户端库,用于与 RailWise API 服务进行交互。SDK 提供了完整的类型定义、请求封装和错误处理,适用于 Node.js 和浏览器环境。

特性 说明
完整类型支持 所有 API 请求和响应均提供 TypeScript 类型定义
Promise 异步 基于 Promise 的异步 API,支持 async/await
自动重试 内置指数退避重试机制
请求拦截 支持自定义请求和响应拦截器
错误处理 统一的错误类型和详细的错误信息
浏览器兼容 支持现代浏览器和 Node.js 环境
ESM/CJS 双模式 同时支持 ES Module 和 CommonJS
  • 语言:TypeScript 5.0+
  • 运行时:Node.js 18+ / 现代浏览器
  • HTTP 客户端:原生 fetch(Node.js 18+)/ 可配置自定义客户端
  • 打包:Rollup + TypeScript
Terminal window
# 使用 npm
npm install @railwise/sdk
# 使用 yarn
yarn add @railwise/sdk
# 使用 pnpm
pnpm add @railwise/sdk
# 使用 bun
bun add @railwise/sdk
依赖 最低版本 说明
Node.js 18.0.0 运行时环境
TypeScript 5.0.0 类型系统(开发依赖)
Terminal window
# 检查当前版本
npm list @railwise/sdk
# 更新到最新版本
npm update @railwise/sdk
# 安装特定版本
npm install @railwise/sdk@1.2.0
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 次
});
import { RailWiseClient } from '@railwise/sdk';
// 从环境变量读取配置
const client = new RailWiseClient({
apiKey: process.env.RAILWISE_API_KEY!,
baseURL: process.env.RAILWISE_API_URL,
});
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();
const projects = await client.projects.list({
status: 'active', // 'active' | 'paused' | 'completed' | 'all'
limit: 50, // 1-200
offset: 0, // 分页偏移
});
// 返回类型:ListProjectsResponse
interface ListProjectsResponse {
total: number;
items: Project[];
hasMore: boolean;
}
const project = await client.projects.get('PRJ-A1B2C3D4', {
includePoints: true, // 包含测点信息
includeDevices: false, // 包含设备信息
});
// 返回类型:ProjectDetail
interface 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[];
}
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,
});
// 返回类型:MonitoringDataResponse
interface MonitoringDataResponse {
projectId: string;
dataType: DataType;
timeRange: {
start: Date;
end: Date;
};
totalRecords: number;
points: MonitoringPointData[];
summary: {
normalCount: number;
yellowWarningCount: number;
orangeWarningCount: number;
redWarningCount: number;
};
}
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, // 是否包含原始观测数据
});
const devices = await client.devices.list({
projectId: 'PRJ-A1B2C3D4', // 可选
deviceIds: ['DEV-TS-001'], // 可选
});
// 返回类型:DeviceListResponse
interface DeviceListResponse {
devices: Device[];
summary: {
total: number;
online: number;
offline: number;
warning: number;
};
}
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,
},
});
// 返回类型:CoordinateTransformResult
interface 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, // 预测天数
});
// 返回类型:DeformationAnalysisResult
interface 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;
};
}
import { RailWiseClient } from '@railwise/sdk';
const client = new RailWiseClient({
apiKey: 'rw_live_xxxxxxxxxxxxxxxx',
// 自定义 fetch 实现
fetch: customFetch,
// 或自定义 axios 实例
httpClient: axiosInstance,
});
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);
}
);
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';
},
});
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);
}
}
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;
}
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'
);
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 小时检查一次

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';

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>
);
}

本文档由 RailWise 技术文档团队维护,最后更新于 2025-01-15。

引用与复核把知识带回真实工程判断

引用时保留页面与来源线索;涉及标准条文、阈值、频率和项目结论,请回到现行依据与责任人复核。

查看 Agent 使用规则